0

爲防止ASP.NET MVC從得到nullstring特性,我們可以將此註釋添加到string屬性:如何添加屬性註釋全球

[DisplayFormat(ConvertEmptyStringToNull = false)] 

我要找的,是這個全球(在整個項目中)。所以,我試圖創建一個自定義的模型綁定:

public class NotNullStringModelBinder : DefaultModelBinder { 

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { 
     if(controllerContext == null) 
      throw new ArgumentNullException("controllerContext"); 
     if(bindingContext == null) 
      throw new ArgumentNullException("bindingContext"); 
     var providerResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
     if(providerResult == null) 
      return string.Empty; 
     var attemptedValue = providerResult.AttemptedValue; 
     return attemptedValue ?? string.Empty; 
    } 

} 

我在(global.asax).Application_Start()添加了這個:

ModelBinders.Binders.Add(typeof(string), new NotNullStringModelBinder()); 

但它不工作,我得到null在所有型號空字符串。我錯過了什麼?請任何想法嗎?

+0

http://stackoverflow.com/questions/7490210/asp-net-mvc-3-bind-string-property-as-string-empty-instead-of的可能重複-null – Kell

回答

1

感謝@Kell似乎所有我需要做的是這樣的:

public class NotNullStringModelBinder : DefaultModelBinder { 

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { 
     bindingContext.ModelMetadata.ConvertEmptyStringToNull = false; 
     return base.BindModel(controllerContext, bindingContext); 
    } 

} 
+1

不錯。我認爲我更喜歡EmptyStringModelBinder的名字,儘管:) – Kell