为防止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