2

How do controllers know which views to return? I thought it was by naming convention, but I have seen instances, for example in the Nerd Dinner application, where the names don't match. Where or how do I see this mapping? Thanks.

3 Answers 3

6
public class EmployeesController
{
    public ViewResult Index()
    {
        return View("CustomerName");
    }
}

Will search for:

Views/Employees/CustomerName.aspx
Views/Employees/CustomerName.ascx
Views/Shared/CustomerName.aspx
Views/Shared/CustomerName.ascx

That's pretty much it..

When you just return View(); without specifying a name, it searched for the view with the same name as the controlleraction. In this case, Index.aspx

4
  • The parameter you're passing to View(), is that meant to be the name that it will search for? Also, is there a way I can tell a controller to look for a view in a specific area?
    – Crios
    Aug 6, 2009 at 14:41
  • The parameter is the name of the view e.g. CustomerName = CustomerName.aspx. As far as I know the locations that mvc looks in is hardcoded, but you can customise it developing a ViewEngine. ViewEngines.Engines.Add(new MyCusyomViewEngine()); //Global.asax.cs Aug 6, 2009 at 14:45
  • the locations are indeed hardcoded with the default viewengine. And the parameter is indeed the name of the view. It is considered best practice to always specify the name of the view because that way you can unit test it. Aug 6, 2009 at 14:56
  • You might want to correct your code. It needs to be return View("CustomerName"); Minor, I know! :) Aug 6, 2009 at 19:05
2

There are three ways to specify a view name.

By Convention

public ActionResult MyAction {
  return View()
}

That will look for a view with the name of the action method, aka "MyAction.ascx" or "MyAction.aspx"

** By Name **

public ActionResult MyAction {
  return View("MyViewName")
}

This will look for a view named "MyViewName.ascx" or "MyViewName.aspx".

** By application path **

public ActionResult MyAction {
  return View("~/AnyFolder/MyViewName.ascx")
}

This last one only looks in this one place, the place you specified.

0

It is based on the name of the Action in the Controller. Here's an example:

I have a controller named UserController.

One of my actions on that controller is named Index.

When I say return View();

It will look in the Views directory, in the User folder, for Index.aspx or Index.ascx

It will also look in the Shared folder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.