Given a class
public class Person
{
// Some general properties
public List<Hobby> Hobbies { get; set; }
}
public class Hobby
{
// Some properties e.g. Name, etc.
}
static List<Hobby> AllHobbies { get; }
Is it possible to create a view that allows the user to select his hobbies using model binding?
It would certainly be possible in the view to loop through AllHobbies and render an <input type="checkbox" /> for each, then wire up the selected values by hand in the postback controller. It seems that this should be doable with model binding, but I don’t see how.
Sure, I would recommend you using editor templates.
Let’s suppose that a hobby has a name and a boolean field indicating whether it was selected by the user:
then a controller to feed the model into the view and process the form submission:
then a view containing the form allowing the user to select hobbies:
and a corresponding editor template which will automatically be rendered for each element of the
Hobbiescollection (~/Views/Home/EditorTemplates/Hobby.cshtml-> notice that the name and location of the template is important):For more advanced editing scenarios I would recommend you going through the Steven Sanderson’s blog post on this topic.