usefulBee usefulBee - 2 months ago 8
C# Question

Using C# 6 String interpolation in Razor the Correct Way

Example:

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


Result:

$'{34645}_{71}'


Expected:

34645_71


Update:
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

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).

Edit:

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.