必须的属性和复杂类型MVC 5
问题描述:
我有一种类型定义为必须的属性和复杂类型MVC 5
public class Autocomplete
{
public Guid Id { get; set; }
public string Label { get; set; }
}
我然后有这种类型的模型作为
public class MPEngagementActivity : IActivity
{
[UIHint("Hidden")]
public Guid Id { get; set; }
[UIHint("Hidden")]
//TODO: GET THIS FROM THE LOGGED IN USER
public Guid CreatedBy { get; set; }
[UIHint("Hidden")]
public int ActivityType { get; set; }
[Required(ErrorMessage = "Please select an Organisation")]
[Display(Name="Constituency")]
public Autocomplete Organisation { get; set; }
[UIHint("ReadOnly")]
[Display(Name = "MP Office Default Contact")]
public String DefaultContact { get; set; }
[Display(Name = "MP Contact")]
public Autocomplete MainContact { get; set; }
}
正如可以看到的属性之一被标记为但是当测试模型即使在表单中没有设置属性时也会返回有效状态,但该标识将返回为0,并且标签为空。
我该如何获得mvc来正确验证它?
答
坐落在类的属性
public class Autocomplete
{
[Requried]
public Guid Id { get; set; }
[Required]
public string Label { get; set; }
}
答
public class Autocomplete
{
public Guid Id { get; set; }
public string Label { get; set; }
// This should do the trick with the standard Required attribute
public static implicit operator string(Autocomplete ac)
{
return ac.Label;
}
// Optionally, if you want to use a custom required instead, this may be more correct
public override string ToString()
{
return Label;
}
}
的[必需]属性,那么你只需把[Required]
属性上3210财产。
这将使所有需要的自动完成属性。 – franklores 2014-10-30 14:03:54