Steve Chambers
Steve Chambers

Reputation: 39394

Why is Controller.View returning null?

I'm unit testing someone else's ASP.Net MVC4 Controller action method. Its last line is:

return this.View("ConfirmAddress", addressModel);

This returns null in my unit test. The Controller.View documentation says the first parameter is a view name but I can't step into this method to find out why null is returned. A ConfirmAddress.cshtml exists in the Views folder but there's also a ConfirmAddress(AddressModel am) action in the controller.

Can anyone tell from this what it should be doing (e.g. perhaps use RedirectToAction instead???) Have tried to keep this short but could provide more info if needed...

Upvotes: 0

Views: 876

Answers (2)

Nick Albrecht
Nick Albrecht

Reputation: 16928

It's possible that the View method is overridden. Try removing the this quantifier.

return View("ConfirmAddress", addressModel);

Upvotes: 1

Erik Schierboom
Erik Schierboom

Reputation: 16636

I have looked at the official source code of the Controller class to see what happens when View is called. It turns out, all the different View method overloads ultimately call the following method:

protected internal virtual ViewResult View(string viewName, string masterName, object model)
{
    if (model != null)
    {
        ViewData.Model = model;
    }

    return new ViewResult
    {
        ViewName = viewName,
        MasterName = masterName,
        ViewData = ViewData,
        TempData = TempData,
        ViewEngineCollection = ViewEngineCollection
     };
}

This method (and thus all the other overloads) will never return NULL, although it could throw an exception. It is virtual though, which means that the code your are calling might override it with a custom implementation and return NULL. Could you check if the View method is overridden anywhere?

Upvotes: 2

Related Questions