您可以使用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>