爲防止ASP.NET MVC從得到null
爲string
特性,我們可以將此註釋添加到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
在所有型號空字符串。我錯過了什麼?請任何想法嗎?
http://stackoverflow.com/questions/7490210/asp-net-mvc-3-bind-string-property-as-string-empty-instead-of的可能重複-null – Kell