usefulBee usefulBee - 11 months ago 42
C# Question

Using C# 6 String interpolation in Razor the Correct Way


<button data-value="$'{@item.CustomerID}_{@item.CustomerType}'"></button>





Had to Enable C#6 and install the appropriate package for smdrager last two techniques to work. In VS2015>>Click Project Menu>>Click Enable 6#

Answer Source

In the example you provided, string interpolation is not necessary. Using standard razor syntax, you can get the result you want with:

<button data-value="@(item.CustomerID)_@item.CustomerType"></button>

Which will produce<button data-value="34567_123"></button>

The equivallent with interpolation would be:

@Html.Raw($"<button data-value='{item.CustomerID}_{item.CustomerType}'></button>")

But you lose out on HTML encoded to prevent script injection (though this seems unlikely with the data types you are dealing with).


If you want to get completely wacky, you can mix both.

<button data-value="@($"{item.CustomerID}_{item.CustomerType}")"></button>

But that is more verbose and difficult to read.