views:

44

answers:

1

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?

+3  A: 

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?

statichippo
Yeah, that's what I thought. I didn't realize that default value for the string type is null, not String.Empty though. No, it's not the case for the IsNullOrEmpty method, I have NOT NULL columns in my SQL table, so I get an exception when there'are null strings. So I guess I'll have to continue to use the ?? "" operator. Thanks!
Alex
You might also use a property with a backing store and return string.empty instead of null from the ViewModel, eg:
statichippo
woops! here's some psuedocode: private string _text; public string Text { get { return _text; } set { _text = value ?? string.empty; }} -- something like that
statichippo