MVC Foolproof NuGetを使用すると、簡単に実現できます。
インストールするだけです:
install-package foolproof
これで、次のモデルを作成できます。
public class TestModel
{
public Guid Id { get; set; }
public string Question { get; set; }
[RequiredIf("Required", true)]
public string Answer { get; set; }
public bool Required { get; set; }
}
public class TestViewModel
{
public string TestName { get; set; }
public List<TestModel> Tests { get; set; }
}
コントローラー:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new TestViewModel
{
TestName = "The test",
Tests = new[]
{
new TestModel { Id = Guid.NewGuid(), Question = "q1", Required = true },
new TestModel { Id = Guid.NewGuid(), Question = "q2", Required = true },
new TestModel { Id = Guid.NewGuid(), Question = "q3", Required = false },
new TestModel { Id = Guid.NewGuid(), Question = "q4", Required = true },
}.ToList()
};
return View(model);
}
[HttpPost]
public ActionResult Index(TestViewModel model)
{
return View(model);
}
}
対応する~/Views/Index.cshtml
ビュー:
@model TestViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/mvcfoolproof.unobtrusive.min.js")" type="text/javascript"></script>
<h2>@Html.DisplayFor(x => x.TestName)</h2>
@using (Html.BeginForm())
{
@Html.HiddenFor(x => x.TestName)
@Html.EditorFor(x => x.Tests)
<button type="submit">OK</button>
}
最後に、TestModel のカスタム エディター テンプレート ( ~/Views/Home/EditorTemplates/TestModel.cshtml
):
@model TestModel
<div>
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.Required)
@Html.HiddenFor(x => x.Question)
@Html.LabelFor(x => x.Answer, Model.Question)
@Html.EditorFor(x => x.Answer)
@Html.ValidationMessageFor(x => x.Answer)
</div>