Asp.net mvc 3 数据注释在视图模型中不起作用

Asp.net mvc 3 数据注释在视图模型中不起作用,asp.net-mvc-3,Asp.net Mvc 3,我有几个不同的模型,这些模型的属性都用数据注释进行了修饰以进行验证 public class BillingModel { [Required, DisplayName("First Name")] public string FirstName { get; set; } [Required, DisplayName("Last Name")] public string LastName { get; set; } } public cla

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

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)
它们呈现如下:

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)

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

您还需要在视图中放置以下
元素(如果您要在所有视图中使用客户端验证,最好是_layout.cshtml视图):


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

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


这就是使数据注释能够对呈现的html产生影响的原因。

例如,一旦将所需的数据注释放入视图模型的字段中
如果它不起作用,只需在使用ViewModel的视图页面的部分脚本中这样写: [![在此处输入图像描述][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>


我的问题是,这些对象是实体框架对象,我为其创建了元数据,但将分部类放在了错误的命名空间中。这个答案与已接受的答案一样重要,您需要在web配置中使用JS和这些设置才能使其正常工作。