Crios
Crios

Reputation: 237

asp.net mvc - Views and Controllers

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.

Upvotes: 2

Views: 160

Answers (3)

Haacked
Haacked

Reputation: 59061

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.

Upvotes: 2

Thomas Stock
Thomas Stock

Reputation: 11296

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

Upvotes: 6

Mark Sherretta
Mark Sherretta

Reputation: 10230

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.

Upvotes: 0

Related Questions