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

Asp.net mvc 使用mvc4创建动态控件并仅对某些字段应用验证,asp.net-mvc,validation,c#-4.0,data-annotations,Asp.net Mvc,Validation,C# 4.0,Data Annotations,我正在使用MVC4构建一个应用程序,它是一个问题生成器,允许用户提出一系列问题,并在需要或不需要时设置真/假 我现在开始生成问题,供用户回答问题 我想同时启用服务器端和客户端验证 将必填字段应用于设置为必填的问题的最佳方法是什么 如果我有一个简单的模型和视图模型 public class TestModel { public Guid Id { get; set; } public string Question { get; set; } public bool Re

我正在使用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; }
}
公共类测试模型
{
公共Guid Id{get;set;}
公共字符串问题{get;set;}
需要公共bool{get;set;}
}
公共类TestViewModel
{
公共字符串TestName{get;set;}
公共列表测试{get;set;}
}
我不能只向Question属性添加[Required]属性


是否可以仅将validate应用于所需属性设置为true的qeustions?

使用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; }
}
相应的
~/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>
}

您可以通过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; }
}
相应的
~/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>
}

哇!谢谢你,达林,给了我这么详细的回答。我很感激你花了这么多时间。哇!谢谢你,达林,给了我这么详细的回答。我很感激你花了这么多时间。