Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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's last two techniques to work. In VS2015>>Click Project Menu>>Click Enable 6#

like image 886
usefulBee Avatar asked Sep 20 '16 19:09

usefulBee


People also ask

What does %C do in C?

Show activity on this post. %d is used to print decimal(integer) number ,while %c is used to print character . If you try to print a character with %d format the computer will print the ASCII code of the character.

What is %d in C programming?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.

Is C useful now?

The C programming language has been alive and kicking since 1972, and it still reigns as one of the fundamental building blocks of our software-studded world.

Where is C most used?

C is commonly used on computer architectures that range from the largest supercomputers to the smallest microcontrollers and embedded systems. A successor to the programming language B, C was originally developed at Bell Labs by Ritchie between 1972 and 1973 to construct utilities running on Unix.

Why is C good for beginners?

The programs that you write in C compile and execute much faster than those written in other languages. This is because it does not have garbage collection and other such additional processing overheads. Hence, the language is faster as compared to most other programming languages.


1 Answers

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)[email protected]"></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.

like image 190
smdrager Avatar answered Sep 28 '22 01:09

smdrager