如何全局添加属性注释
本文关键字:注释 属性 添加 何全局 | 更新日期: 2023-09-27 18:07:07
防止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
。我错过了什么?有什么想法吗?
感谢@Kell似乎所有我需要做的是:
public class NotNullStringModelBinder : DefaultModelBinder {
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;
return base.BindModel(controllerContext, bindingContext);
}
}
答案在这里:ASP。Net MVC 3绑定字符串属性为字符串。空而不是空
(问题中的第二个答案)似乎您必须绑定到属性绑定上下文,而不是模型绑定上下文