views:

87

answers:

3

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.

+6  A: 
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

Thomas Stock
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
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
Nick Clarke
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.
Thomas Stock
You might want to correct your code. It needs to be return View("CustomerName"); Minor, I know! :)
Dan Atkinson
A: 

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.

Nebakanezer
A: 

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.

Haacked