ASP.Net MVC 3 bind string property as string.Empty instead of null

后端 未结 2 902
伪装坚强ぢ
伪装坚强ぢ 2021-02-14 05:41

model is

public partial class BilingualString 
{ 
    public string RuString { get; set; } 
    public string EnString { get; set; } 
} 

public partial class Me         


        
相关标签:
2条回答
  • 2021-02-14 06:28

    Use this:

        [DisplayFormat(ConvertEmptyStringToNull=false)]
        public string RuString { get; set; }
    

    OR

        private string _RuString;
        public string RuString {
            get {
                return this._RuString ?? "";
            }
            set {
                this._RuString = value ?? "";
            }
        }
    
    0 讨论(0)
  • 2021-02-14 06:38

    old question, but here's an answer anyway :)

    The issue seems to be that the ConvertEmptyStringToNull is set on the model binding context, not the property binding context.

    Inside the DefaultModelBinder, it calls BindProperty for each property of the model, and doesn't recurse simple objects like strings/decimals down to their own call of BindModel.

    Luckily we can override the GetPropertyValue instead and set the option on the context there.

    public class EmptyStringModelBinder : DefaultModelBinder
    {
       protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
       {
           bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;
           return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
       }
    } 
    

    Worked for me :)

    [edit] As pointed out in comments.. This model binder will only work if registered, so after adding class, be sure to call

    ModelBinders.Binders.Add(typeof(string), new EmptyStringModelBinder());
    

    in the Application_Start() method of Global.asax.cs

    0 讨论(0)
提交回复
热议问题