Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

web api action parameter convert empty string parameter to null

I have a some web Api actions with a lot of string parameter. for some of these parameters , client sends empty string instead of null but I need to save null in database in case of empty string. I tried with model binder and JSONconvertor but failed.

FYI; I need a generic solution as I don't want check parameter inside the method body and replace them with null.

like image 648
behtash Avatar asked Oct 20 '25 14:10

behtash


2 Answers

You can use the DisplayFormat attribute on your string properties to automatically convert empty strings to null.

[DisplayFormat(ConvertEmptyStringToNull = true)]
public string MyString { get; set; }
like image 92
Justin Avatar answered Oct 23 '25 05:10

Justin


Thanks Sarathy , your solution may also work but I ended with following solution: 1)Creating custom model binder like following

 public class EmptyStringModelBinder : System.Web.Mvc.IModelBinder
    {
        public object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            string key = bindingContext.ModelName;
            ValueProviderResult val = bindingContext.ValueProvider.GetValue(key);
            if (val != null)
            {
                var s = val.AttemptedValue as string;
                if (s != null && (s.IsEmpty() || s.Trim().IsEmpty()))
                {
                    return null;
                }

                return val.AttemptedValue;
            }

            return null;
        }
    }

2)Mark action method parameter with ModelBinder attribute

public ActionResult UpdateAttribute(int id, 
                                     int AttributeTypeId,
                                     int? Number_Value, 
                                     decimal? Money_Value,
                                            [ModelBinder(typeof(EmptyStringModelBinder))]string Text_Value)

or you could add this model binder at configuration. it will inspect all string parameters and replace empty string with null(maybe not desired)

like image 33
behtash Avatar answered Oct 23 '25 03:10

behtash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!