I’m using C#.NET MVC3 (Razor) to create a simple form. But in that form i need to print the content of a list in the form of radiobuttons. But i’m not sure how this works:
@using(Html.BeginForm("Method", "Controller", FormMethod.Post))
{
foreach (Items item in Model.Items)
{
<div>
@Html.RadioButtonFor(item->itemId)
@Html.LabelFor(item->description)
</div>
}
}
But this doesn’t work.
I can probably use normal html tags to create the radio buttons. But then the data won’t be auto saved in the right?
How can i make this work?
I would recommend you using editor templates instead of writing those loops:
and now define a corresponding editor template which will automatically be rendered for each element of the model (
~/Views/Shared/EditorTemplates/ItemViewModel.cshtml):Notice that you must pass a second argument to the
Html.RadioButtonForhelper in addition to the lambda expression that picks the corresponding view model property. This argument represents the value that will be sent to the server and bound to the corresponding property if the user checks this radio button when the form is submitted.Also notice that this works by convention. If we assume that the Items property in your main view model is of type
IEnumerable<ItemViewModel>then the corresponding editor template that you must define and which will be rendered for each element of this collection is~/Views/Shared/EditorTemplates/ItemViewModel.cshtmlor~/Views/CurrentController/EditorTemplates/ItemViewModel.cshtmlif you don’t want this template to be shared between multiple controllers.