【发布时间】:2016-09-14 09:27:53
【问题描述】:
为了防止 ASP.NET MVC 为string 属性获取null,我们可以在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 用于所有模型中的空字符串。我错过了什么?请问有什么办法吗?
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-5 data-annotations model-binding