我有一个定义为
的类型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; }
}
正如您所看到的,其中一个属性被标记为必需,但是当测试模型返回为有效时,即使未在表单中设置该属性,该ID也将返回为0并且标签为空。 / p>
如何让mvc正确验证?
答案 0 :(得分:0)
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]
属性放在Autocomplete
属性上。
答案 1 :(得分:-1)
在类的属性
上设置[Required]属性 public class Autocomplete
{
[Requried]
public Guid Id { get; set; }
[Required]
public string Label { get; set; }
}