使用mvc4创建动态控件并仅对某些字段应用验证

时间:2012-09-11 22:20:13

标签: asp.net-mvc validation c#-4.0 data-annotations

我正在使用MVC4构建一个应用程序,它是一个问题生成器,允许用户提出一堆问题,如果需要,可以设置为true / false。

我现在正处于为用户回答问题做好准备的问题。

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

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

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

 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; }
}

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

是否可以仅对必需属性设置为true的qeustions应用验证?

1 个答案:

答案 0 :(得分: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>