0

为防止ASP.NET MVC从得到nullstring特性,我们可以将此注释添加到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在所有型号空字符串。我错过了什么?请任何想法吗?

+0

http://stackoverflow.com/questions/7490210/asp-net-mvc-3-bind-string-property-as-string-empty-instead-of的可能重复-null – Kell

回答

1

感谢@Kell似乎所有我需要做的是这样的:

public class NotNullStringModelBinder : DefaultModelBinder { 

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

} 
+1

不错。我认为我更喜欢EmptyStringModelBinder的名字,尽管:) – Kell