如何全局添加属性注释

时间:2016-09-14 09:27:53

标签: c# asp.net-mvc asp.net-mvc-5 data-annotations model-binding

为防止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空字符串。我错过了什么?好吗?

2 个答案:

答案 0 :(得分:1)

答案在这里:ASP.Net MVC 3 bind string property as string.Empty instead of null

(问题中的第二个答案)似乎你必须绑定到属性绑定上下文,而不是模型绑定上下文

答案 1 :(得分:1)

感谢@Kell似乎我需要做的就是:

public class NotNullStringModelBinder : DefaultModelBinder {

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

}