4

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.

2
  • I have answered something similar to this for the question in stackoverflow.com/questions/28430031/…. Instead of creating a new instance, you can find only the empty string parameters (if the parameter type is string) and replace them with null in the action arguments dictionary. Commented Feb 11, 2015 at 12:14
  • Thanks mate. your solution also works but I developed a custom model binder. see below. Thanks again Commented Feb 12, 2015 at 1:37

3 Answers 3

4

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; }
Sign up to request clarification or add additional context in comments.

2 Comments

I tested this right before giving you a downvote. If you can point to a working example I'll gladly revert it to a upvote. I needed this exact functionality and wasn't able to make it work.
I've just gotten this to work, you must put this on your entity framework poco (in my case Code First database entity). My view model parsed it in as an empty string "".. With this annotation when it came to try persist it to the database it changed it to null. Thank you Justin.
3

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)

Comments

3

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.

1 Comment

+1. It is handy for validation tasks with WebAPI where it is usually required to have everything in place before a check ModelState.IsValid. I had the identical case like Sean's requirement. But! there were some thousand models with up to 150 properties. Instead of doing work with DisplayFormat for each property, I came to such solution: link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.