2

我正在使用 MVC4 构建一个应用程序,它是一个问题生成器,允许用户提出一堆问题,并在是否需要时设置真/假。

我现在正在生成准备好供用户回答问题的问题。

我想同时启用服务器端和客户端验证。

将必填字段应用于已设置为必填的问题的最佳方法是什么?

如果我有一个简单的模型和视图模型,例如

 public class TestModel
{
    public Guid Id { get; set; }
    public string Question { get; set; }
    public bool Required { get; set; }
}

public class TestViewModel
{
    public string TestName { get; set; }
    public List<TestModel> Tests { get; set; }
}

我不能只向 Question 属性添加 [Required] 属性

是否可以仅将验证应用于必需属性设置为 true 的问题?

4

1 回答 1

4

您可以使用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>
于 2012-09-12T08:51:41.553 回答