MVC ViewModel [必需] DropDownListFor

时间:2012-10-05 21:37:54

标签: asp.net-mvc

我有一个viewmodel,我有一个名为Type be的字段:

    [Required]  
   public string Type{ get; set; } 

我在不同的页面上使用此viewmodel,但在某些情况下,不需要Type。 我想知道如何告诉页面没有Type是必需的。

我尝试的是放

     @Html.HiddenFor(model => model.Type)

但这没效果。

2 个答案:

答案 0 :(得分:1)

您无法使用RequiredAttribute

执行此操作

编写/获取自定义条件属性,例如RequiredIfAttribute(示例here

或使用FluentValidation代替DataAnnotations。

或使用不同的ViewModels。

答案 1 :(得分:1)

如果您想使用相同的视图模型出于任何原因查看使用foolproof库,那么foolproof旨在扩展ASP.NET MVC中提供的Data Annotation验证。最初的工作重点是增加或有验证。

他所需的属性是:

[RequiredIf]
[RequiredIfNot]
[RequiredIfTrue]
[RequiredIfFalse]
[RequiredIfEmpty]
[RequiredIfNotEmpty]
[RequiredIfRegExMatch]
[RequiredIfNotRegExMatch]

Foolproof的美妙之处在于它支持使用开箱即用的不显眼技术进行客户端验证。

所以在你的情况下

[RequiredIfTrue("ShouldValidateType"]  
public string Type{ get; set; } 

public bool ShouldValidateType {get; set;}

属性类型仅验证ShouldValidateType是否为真。