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.
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; }
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With