これはエディタテンプレートの候補のようです。いつものように私たちは、ビューモデルを設計することにより起動します。その後、
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)
いくつかのコードを表示できますか? ASP.NET MVC 3はフォームフィールドを自動的にモデルにマップすることができます。関心リストに関するすべてのものなので、ビューとモデルの適切な部分を表示してください。 – Rhapsody