Why do I get null instead of empty string when receiving POST request in from Razor View?

Alex picture Alex · Sep 4, 2010 · Viewed 37.5k times · Source

I used to receive empty string when there was no value:

[HttpPost]
public ActionResult Add(string text)
{
    // text is "" when there's no value provided by user
}

But now I'm passing a model

[HttpPost]
public ActionResult Add(SomeModel Model)
{
    // model.Text is null when there's no value provided by user
}

So I have to use the ?? "" operator.

Why is this happening?

Answer

Michael Jubb picture Michael Jubb · Feb 17, 2012

You can use the DisplayFormat attribute on the property of your model class:

[DisplayFormat(ConvertEmptyStringToNull = false)]