【问题标题】:How to add property annotation globally如何全局添加属性注释
【发布时间】: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


【解决方案1】:

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

public class NotNullStringModelBinder : DefaultModelBinder {

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

}

【讨论】:

  • 不错。我想我更喜欢 EmptyStringModelBinder 这个名字 :)
【解决方案2】:

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

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

【讨论】:

  • 谢谢。但不起作用。但是,帮助我明白了这个想法。请看我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-09
  • 2017-06-07
  • 1970-01-01
  • 1970-01-01
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多