asp.net-mvc-3actionresult

How does ASP.Net MVC determine the view to use from a controller?


I have a controller that returns an ActionResult. Specifically, it calls return View(someViewModel) at the end of the method. Here's the method signature:

protected ActionResult SomeControllerMethod(AViewModel someViewModel)

I've subsequently inherited from AViewModel (AnInheritedViewModel), added a few new properties to the class and am now passing it into SomeControllerMethod.

Now, at the return statement at end of this method I get an error about how the view can't be found. That's fair enough, but I'm not sure how this all works by default.

The view names MVC tells me it's looking for don't line up with the name of either the controller method or the model type. Going by the same pattern, there are no views corresponding to the name of the original model either. So I'm not sure how MVC decides which view it's going to use?


Solution

  • When you

    public ActionResult SomeControllerMethod()
    {
        return View();
    }
    

    MVC tries to look for a view named "SomeControllerMethod.cshtml". It uses the name of the method as a guide for looking for a view file.

    You can override this by:

    public ActionResult SomeControllerMethod()
    {
        return View("MyView");
    }
    

    and MVC will thus try to find "MyView.cshtml".