【问题标题】:Data annotations not working in view model数据注释在视图模型中不起作用
【发布时间】:2012-01-06 19:19:28
【问题描述】:

我有几个不同的模型,它们的属性都用数据注释进行了修饰以进行验证。

public class BillingModel
{
    [Required,
    DisplayName("First Name")]
    public string FirstName { get; set; }

    [Required,
    DisplayName("Last Name")]
    public string LastName { get; set; }
}

public class CustomerModel
{
    [Required,
    DisplayName("Address")]
    public string Adress { get; set; }

    [Required,
    DisplayName("City")]
    public string City { get; set; }
}

当我将它们放在这样的视图模型中时:

public class OrderViewModel
{
    public BillingModel Billing { get; set; }
    public CustomerModel Customer { get; set; }
}

它们的渲染是这样的:

<input id="Business_FirstName" name="Business.FirstName" type="text" value="" />

<input id="Business_LastName" name="Business.LastName" type="text" value="" />

我的剃须刀看起来像这样:

@Html.TextBoxFor(x => x.Business.FirstName)
@Html.TextBoxFor(x => x.Business.LastName)

我有许多属性需要存在于它们自己的类中,因为每个类都包含特定的方法。即使我将[Required] 放在视图模型中的每个属性上,它仍然不起作用。

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    您还需要将以下 &lt;script /&gt; 元素放在您的视图中(如果您将在所有视图中使用客户端验证,最好是 _layout.cshtml 视图):

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

    相应地修改路径。但这应该可以让您的验证启动并运行。

    另外,在您的视图中使用ValidationMessageFor()。像这样:

    @Html.TextBoxFor(x => x.Business.FirstName)
    @Html.ValidationMessageFor(x => x.Business.FirstName)
    
    @Html.TextBoxFor(x => x.Business.LastName)
    @Html.ValidationMessageFor(x => x.Business.LastName)
    

    【讨论】:

    • 我的问题是这些对象是我为其创建元数据的实体框架对象,但将部分类放在错误的命名空间中。
    【解决方案2】:

    对于遇到此问题的其他人,除了其他答案外,您还需要启用以下 web.config 设置:

    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    

    这使得数据注释能够对呈现的 html 产生影响。

    【讨论】:

    • 这个答案和已经被接受的答案一样重要,你需要 JS 和 web-config 中的这些设置才能正常工作。
    【解决方案3】:

    例如,一旦您将所需的数据注释放在视图模型的 You 字段中
    而且,如果它不起作用,只需在您正在使用 ViewModel 的 View 页面的部分脚本中编写此代码,如下所示: [![在此处输入图像描述][2]] 我希望可以帮助你! 别忘了使用下面的标签装饰器到字段 @Html.ValidationMessageFor(x => x.Model.Name) 这是脚本:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 2013-06-19
      • 2013-05-27
      相关资源
      最近更新 更多