Кажется, это хороший кандидат на редактирование шаблонов.Как всегда, мы начинаем с разработки модели вида:
public class MyViewModel
{
public string Name { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? DateOfBirth { get; set; }
public string Place { get; set; }
public IEnumerable<InterestViewModel> Interests { get; set; }
}
public class InterestViewModel
{
public int Id { get; set; }
public string InterestLabel { get; set; }
public bool IsSelected { get; set; }
}
, затем контроллера:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Name = "john",
DateOfBirth = new DateTime(1990, 1, 1),
Place = "Spain",
Interests = new[]
{
new InterestViewModel { Id = 1, InterestLabel = "cinema" },
new InterestViewModel { Id = 2, InterestLabel = "sport" },
new InterestViewModel { Id = 3, InterestLabel = "books" },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// TODO: process the results here, the view model will be
// correctly bound
....
}
}
, затем вида (~/Views/Home/Index.cshtml
)
@model MyViewModel
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.Name)
@Html.EditorFor(x => x.Name)
</div>
<div>
@Html.LabelFor(x => x.DateOfBirth)
@Html.EditorFor(x => x.DateOfBirth)
</div>
<div>
@Html.LabelFor(x => x.Place)
@Html.EditorFor(x => x.Place)
</div>
<h2>Interests</h2>
@Html.EditorFor(x => x.Interests)
<button type="submit">OK</button>
}
исоответствующий шаблон редактора, который будет отображаться для каждого элемента коллекции интересов (~/Views/Home/EditorTemplates/InterestViewModel.cshtml
):
@model InterestViewModel
@Html.LabelFor(x => x.IsSelected, Model.InterestLabel)
@Html.CheckBoxFor(x => x.IsSelected)
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.InterestLabel)