I currently have an object Tag defined as follows:
public class Tag
{
public string Name { get; set; }
}
Now, this is a collection property of a Model which I’m defining as:
public class MyModel
{
public string Name { get; set; }
public IList<Tag> Tags { get; set; }
}
In my view I have the following code:
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
</div>
<div>
<!--
Here I'd like a collection of checkbox inputs, where the selected names
get passed back to my controller via the IList<Tag> collection
-->
</div>
<input type="submit" value="Submit" />
}
How do I return the selected items on my checkbox group (specified in comments) via the IList collection of my model?
Use Editor Templates
For having the Checkbox, Add another Proeprty to your
Tagclasss to specify whether it is selected or not.Now from your
GETAction, you can set a List of Tags in your Model’sTagsProperty and sent it to the View.Now Let’s create an Editor Template, Go to The
View/YourControllerNameand Create a Folder calledEditorTemaplatesand Create a new View there with the same name as of the Property type (Tag.cshtml).Add this content to the new editor template now.
Now in your Main View, Call your Editor template using the
EditorForHtml Helper method.Now when You Post the Form, Your Model will have the Tags Collection where the Selected Checkboxes will be having a True value for the
IsSelectedProperty.Like this