MVC Disable Converting Empty String to Null

Some joker decided that empty strings passed into an MVC controller should be converted to null by default. One way to avoid this is to decorate the string properties of the model class:

using System.ComponentModel.DataAnnotations;

public class SomeModel {
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string SomeProperty { get; set; }

public JsonResult DoSomething(SomeModel myModel) {
bool isEmpty = (myModel.SomeProperty == string.Empty);
return Json(new { IsEmpty = isEmpty });
Then when you pass in an empty string, it will remain an empty string in the .NET code:

type: "post",
url: "@Url.Action("DoSomething")",
data: JSON.stringify({ SomeProperty: "" }),
dataType: "json",
contentType: "application/json;charset=utf-8;"
}).done(function (result) {

Leave a Reply

Your email address will not be published.