当然,我建议您使用编辑器模板。
让我们假设一个爱好有一个名称和一个布尔字段,指示它是否被用户选择:
public class Hobby
{
public string Name { get; set; }
public bool Selected { get; set; }
}
然后一个控制器将模型输入视图并处理表单提交:
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);
}
}
然后是一个包含允许用户选择爱好的表单的视图:
@model Person
@using (Html.BeginForm())
{
<h2>Hobbies</h2>
@Html.EditorFor(x => x.Hobbies)
<button type="submit">OK</button>
}
和一个相应的编辑器模板,它将为集合的每个元素自动呈现Hobbies
(~/Views/Home/EditorTemplates/Hobby.cshtml
-> 请注意模板的名称和位置很重要):
@model Hobby
<div>
@Html.LabelFor(x => x.Selected, Model.Name)
@Html.HiddenFor(x => x.Name)
@Html.CheckBoxFor(x => x.Selected)
</div>
对于更高级的编辑场景,我建议您阅读 Steven Sanderson关于此主题的博客文章。