2014-05-05 71 views
0

我已經簡單的類代表型號爲什麼有些屬性將isRequired設置爲true?

public class Test{ 
     [Required] 
     [DisplayName("Code")] 
     [RegularExpression(@"^[0-9A-Za-z ]+$", ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName = "GeneralShowModel_Code_Error")] 
     [MaxLength(25, ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName = "GeneralShowModel_Code_Length_Error")] 
     public string Code { get; set; } 

     [Range(0, Int16.MaxValue, ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName = "GeneralShowModel_MaxGuests_Error")] 
     [DisplayName("Max guests")] 
     public long MaxGuests { get; set; } 

     [DisplayName("Pre-registration is closed")] 
     public bool IsPreRegistrationClosed { get; set; } 

     [DisplayName("In test mode")] 
     public bool InTestMode { get; set; } 
} 

我創建簡單的自定義HTML輔助渲染標籤帶班「必要」時,財產已必需屬性

public static class CustomHelper 
{ 
    public static MvcHtmlString RequiredLabelFor<T, TU>(this HtmlHelper<T> helper, 
Expression<Func<T, TU>> expression) 
    { 
     var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData); 
     var isRequired = metaData.IsRequired; 
     var htmlFieldName = ExpressionHelper.GetExpressionText(expression); 
     var label = new TagBuilder("label"); 
     label.SetInnerText(metaData.DisplayName); 

     label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)); 
     if (isRequired) 
     { 
      label.Attributes.Add("class", "required"); 
     } 
     return MvcHtmlString.Create(label.ToString()); 
    } 
} 

我以這種方式使用這個幫手

@Html.RequiredLabelFor(m => m.Code) 

MaxGuests,IsPreRegistrationClosed等沒有必需的屬性,但metaData.IsRequired爲true。如何解決這個障礙?

回答

1

這是因爲MaxGuests是一個原始類型,不允許null值。因此,它是必需的。

試試這個:

public long? MaxGuests { get; set; } 

?long後。這使它可以爲空。

+0

@Victor:試試這個試試嗎? –

+0

非常感謝這個解決方案。我們可以在不更改爲可空類型的情況下執行此操作,只能通過檢查現有的[必需的]屬性? – BILL

+0

@Victor:不是我所知道的。 –

相關問題