22

I have a form that creates a number of checkbox elements using Razor code like this

   foreach (var tag in Model.Tags)
    {
        <input type="checkbox" id="@tag.ID" name="@tag.ID" value="@tag.TagName"/>@tag.TagName<br /
    }

This works but I want the ID's and names to be in this format chkTag[TagID] I've tried this

<input type="checkbox" id="[email protected]" name="[email protected]" value="@tag.TagName"/>

but Razor just treats the whole thing as string and names them [email protected].

So I guess my question is how do I add the dynamic razor ID to the end of my Name and ID's?

Thanks

1
  • why dont you use Html.CheckBoxFor, and specify the name html attribute? and furthermore, use an editor template and save the foreach loop. Commented Jul 27, 2011 at 7:44

2 Answers 2

43

You should use parentheses around tag.ID, like this:

chkTag@(tag.ID)

Full code:

foreach (var tag in Model.Tags)
{
    <input type="checkbox" id="chkTag@(tag.ID)" name="chkTag@(tag.ID)" value="@tag.TagName"/>
}
Sign up to request clarification or add additional context in comments.

Comments

4
@for (int i = 0; i < Model.Tags.Count(); i++)
{

        @Html.CheckBoxFor(model => Model.Tags[i])

}

This should do it normally. It will automatically give the correct name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.