Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor syntax - using two variables in string

Tags:

c#

razor

SomeObject record = new SomeObject();
record.value1 = 1;
record.value2 = "hello";

<td><input type="checkbox" id="[email protected][email protected]" /><td>

What is the proper razor syntax to create a checkbox with an id of "indicator_1_hello"?

When attempting this way, it says the object doesn't contain a definition for value1_ (understandable) and when I tried "[email protected]@[email protected]" if had a runtime error about something named _ not existing in the context (again, understandable).

edit:

As a temporary solution I've done:

SomeObject record = new SomeObject();
record.value1 = 1;
record.value2 = "hello";
var combined = String.Format("{0}_{1}", record.value1, record.value2);

<td><input type="checkbox" id="indicator_@combined" /><td>

I am still curious if you can do it all inline though.

like image 417
Robert Avatar asked Mar 07 '13 18:03

Robert


People also ask

What are the main Razor syntax rules?

Razor code blocks are enclosed in @{ … } Inline expressions (variables and functions) start with @ Code statements end with a semicolon. Variables are declared with the var keyword.

What is Razor syntax in MVC?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.

Which of the following represents Razor syntax?

The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.


1 Answers

@{
    // just for testing
    var record = new { value1 = "foo", value2 = "bar" };
}

<input type="checkbox" id="indicator_@( record.value1 + "_" + record.value2 )">

Gives: <input type="checkbox" id="indicator_foo_bar">

Just make sure that you aren't building an ID which would be better auto-generated by the natural hierarchy of your view model. Most of the time, you shouldn't need to manually construct IDs in your view.

like image 160
Tim M. Avatar answered Sep 30 '22 04:09

Tim M.