有一定的重复自己的风险,我会用以下句子开始我的回答:
与往常一样,在 ASP.NET MVC 应用程序中,您应该使用视图模型。
所以:
public class MyViewModel
{
public string Name { get; set; }
public bool IsChecked { get; set; }
}
然后是控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
// Those are your domain models
// they could come from a database or something
var listA = new[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
var listB = new[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10" };
// Now let's map our domain model to our view model
var model = listB.Select(x => new MyViewModel
{
Name = x,
IsChecked = listA.Contains(x)
});
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<MyViewModel> model)
{
var selectedItems = model.Where(x => x.IsChecked);
var format = string.Join(",", selectedItems.Select(x => x.Name));
return Content("Thank you for selecting " + format);
}
}
然后是相应的视图 ( ~/Views/Home/Index.cshtml
):
@model IEnumerable<MyViewModel>
@using (Html.BeginForm())
{
@Html.EditorForModel()
<button type="submit">OK</button>
}
最后是相应的编辑器模板,它将为模型集合的每个元素自动呈现(~/Views/Home/EditorTemplates/MyViewModel.cshtml
):
@model MyViewModel
<div>
@Html.HiddenFor(x => x.Name)
@Html.LabelFor(x => x.IsChecked, Model.Name)
@Html.CheckBoxFor(x => x.IsChecked)
</div>
渲染结果(如我的 Chrome 浏览器所见)如下所示:
看看使用视图模型有多容易?