问题
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.
回答1:
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:
public class Hobby
{
public string Name { get; set; }
public bool Selected { get; set; }
}
then a controller to feed the model into the view and process the form submission:
public class HomeController : Controller
{
public ActionResult Index()
{
var person = new Person
{
Hobbies = new[]
{
new Hobby { Name = "hobby 1" },
new Hobby { Name = "hobby 2", Selected = true },
new Hobby { Name = "hobby 3" },
}.ToList()
};
return View(person);
}
[HttpPost]
public ActionResult Index(Person person)
{
var selectedHobbies = person
.Hobbies
.Where(x => x.Selected).Select(x => x.Name);
string message = string.Join(",", selectedHobbies);
return Content("Thank you for selecting: " + message);
}
}
then a view containing the form allowing the user to select hobbies:
@model Person
@using (Html.BeginForm())
{
<h2>Hobbies</h2>
@Html.EditorFor(x => x.Hobbies)
<button type="submit">OK</button>
}
and a corresponding editor template which will automatically be rendered for each element of the Hobbies
collection (~/Views/Home/EditorTemplates/Hobby.cshtml
-> notice that the name and location of the template is important):
@model Hobby
<div>
@Html.LabelFor(x => x.Selected, Model.Name)
@Html.HiddenFor(x => x.Name)
@Html.CheckBoxFor(x => x.Selected)
</div>
For more advanced editing scenarios I would recommend you going through the Steven Sanderson's blog post on this topic.
来源:https://stackoverflow.com/questions/10984727/select-items-from-listt-in-mvc-4-using-model-binding