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

asp.net MvcStringRazorNullViewmodel

asp.net Mvc Problem Overview


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?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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

[DisplayFormat(ConvertEmptyStringToNull = false)]

[1]: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.aspx "System.ComponentModel.DataAnnotations.DisplayFormatAttribute"

Solution 2 - asp.net Mvc

The default model binding will create a new SomeModel for you. The default value for the string type is null since it's a reference type, so it's being set to null.

Is this a use case for the string.IsNullOrEmpty() method?

Solution 3 - asp.net Mvc

I am trying this in Create and Edit (my object is called 'entity'):-

        if (ModelState.IsValid)
        {
            RemoveStringNull(entity);
            db.Entity.Add(entity);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(entity);
    }

Which calls this:-

    private void RemoveStringNull(object entity)
    {
        Type type = entity.GetType();
        FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Instance | BindingFlags.GetField | BindingFlags.Public | BindingFlags.NonPublic);
        for (int j = 0; j < fieldInfos.Length; j++)
        {
            FieldInfo propertyInfo = fieldInfos[j];
            if (propertyInfo.FieldType.Name == "String" )
            {
                object obj = propertyInfo.GetValue(entity);
                if(obj==null)
                    propertyInfo.SetValue(entity, "");
            }
        }
    }

It will be useful if you use Database First and your Model attributes get wiped out each time, or other solutions fail.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - asp.net MvcMichael JubbView Answer on Stackoverflow
Solution 2 - asp.net MvchackerhasidView Answer on Stackoverflow
Solution 3 - asp.net Mvcuser2284063View Answer on Stackoverflow