Flavio CF Oliveira
Flavio CF Oliveira

Reputation: 5295

String concatenation with ASP.NET MVC3 Razor

i'm trying to concatenate a string in asp.net mvc 3 razor and i'm getting a little sintax problem with my cshtml.

i what to generate an id for my checkboxes on a foreach statement, and my checkboxes should start with "chk" and what to cancatenate a fieldon the ID, something like that:

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

but or exampple the result for id attribute is: id="chk+8"

how can i just get a result for something like "chk8"?

Upvotes: 14

Views: 23766

Answers (5)

Kalpesh Dabhi
Kalpesh Dabhi

Reputation: 802

Best way to concate any C# variable in rozer view by using string.Format

id="@string.Format("{0}_Title", _Id)" // Apend after
id="@string.Format("Title_{0}", _Id)" // Apend before
id="@string.Format("Title_{0}_Title", _Id)" // Apend Middle

Upvotes: 0

Zandro
Zandro

Reputation: 51

<input type="checkbox" id="chk@(obj.field)" /> should work.

The most direct and clean way to add a prefix a suffix.

@("PREFIX " + obj.field + " SUFFIX")

Upvotes: 5

DanielB
DanielB

Reputation: 20230

<input type="checkbox" id="chk@(obj.field)" /> should work.

Upvotes: 3

Samich
Samich

Reputation: 30175

Just put your variable next to prefix:

<input type="checkbox" id="chk@(obj.field)" />

Upvotes: 39

Stanislav Ageev
Stanislav Ageev

Reputation: 778

Try

<input type="checkbox" id="@("chk" + obj.field)" />

or

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

Upvotes: 10

Related Questions