2014-10-03 55 views
0

我有一種類型定義爲必須的屬性和複雜類型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來正確驗證它?

回答

-1

坐落在類的屬性

public class Autocomplete 
    { 
     [Requried] 
     public Guid Id { get; set; } 
     [Required] 
     public string Label { get; set; } 
    } 
+1

這將使所有需要的自動完成屬性。 – franklores 2014-10-30 14:03:54

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]屬性上​​3210財產。

相關問題