Reputation: 101
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.
Upvotes: 4
Views: 5089
Reputation: 15144
If you use the [Required]
attribute on the string property, but make it nullable in the database, WebApi will convert the empty string it receives in the Json to a null value.
My requirement was for the opposite. I have a non-nullable field in the database, and wanted to save the empty string to the database. For this requirement, I had to remove the [Required]
attribute and add [DisplayFormat(ConvertEmptyStringToNull = false)]
Then the empty strings in the JSON were persisted to the database.
Upvotes: 3
Reputation: 101
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)
Upvotes: 3
Reputation: 69
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; }
Upvotes: 4