adamjford
adamjford

Reputation: 7588

Parameter for action always not null

Here's the code:

public class MessagesController
{
    public virtual ActionResult Compose(ComposeMessageViewModel composeMessageViewModel = null)
    {
        if (composeMessageViewModel == null)
        {
            // never executed as composeMessageViewModel is always not null
            composeMessageViewModel = new ComposeMessageViewModel();
        }

        return View(composeMessageViewModel);
    }
}

And the definition of ComposeMessageViewModel

public class ComposeMessageViewModel
{
    [DisplayName("To:")]
    [NotEmpty] //custom ValidationAttribute
    public IEnumerable<MessageRecipientViewModel> Recipients { get; set; }
    [DisplayName("Subject:")]
    public string Subject { get; set; }
    public string Body { get; set; }
}

The problem is, when I navigate to /Messages/Compose (no query string, no form parameters), I'm expecting the parameter to be null so that no validation errors would occur, but it's an actual object with all its fields/properties set to default values.

This is undesirable as it causes the validation for the model to be executed, when it should not be as nothing has been entered yet!

There's no custom ModelBinder set for this class, and the default ModelBinder has not been changed.

WTF?

Upvotes: 1

Views: 1015

Answers (2)

adamjford
adamjford

Reputation: 7588

The true answer: PEBKAC. I originally had a Send action which, if validation failed, I thought I would have to redirect to the Compose action for some reason instead of just returning the appropriate view with the appropriate ViewModel. Duuuuuuuh. :)

Upvotes: 0

David
David

Reputation: 2038

Isn't that what your code is doing - creating an object with default values?

   if (composeMessageViewModel == null)
   {
        composeMessageViewModel = new ComposeMessageViewModel();
   }

Upvotes: 1

Related Questions