如何全局添加属性注解

How to add property annotation globally

为了防止 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 所有模型中的空字符串。我错过了什么?有什么想法吗?

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

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

感谢@Kell,看来我需要做的就是这个:

public class NotNullStringModelBinder : DefaultModelBinder {

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

}