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?
You can use the
DisplayFormat
attribute on the property of your model class: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?
I am trying this in Create and Edit (my object is called 'entity'):-
Which calls this:-
It will be useful if you use Database First and your Model attributes get wiped out each time, or other solutions fail.