I'm trying out ASP.NET MVC, but, after reading a huge tutorial, I'm slightly confused. I understand how Controllers have Actions that URLs are 开发者_StackOverflowrouted to, but how do home pages work? Is the home page its own controller (e.g. "Home") that has no actions? This sounds correct, but how is it functionality implemented without Actions (no Actions means no methods that call the View Engine)?
In other words, my question is this: how are home pages implemented (in terms of Controllers and Views)? Could you please provide sample code?
"Home" page is nothing more than arbitrary Action
in a specific Controller
which returns a certain View
To set the "Home", page, or better worded, the default page, you need to change the routing info in the Global.asax.cs
file:
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
AreaRegistration.RegisterAllAreas();
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "NotHome", action = "NotIndex", id = "" } // Parameter defaults
);
Notice the route definition:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "NotHome", action = "NotIndex", id = "" } // Parameter defaults
);
This route is a "catch-all" route, meaning it will take any URL and break it down to a specific controller and action and id. If none or one of the routes are defined, it will use the defaults:
new { controller = "NotHome", action = "NotIndex", id = "" }
This says "If someone visits my application, but didn't specify the controller or action, I'm going to redirect them to the NotIndex
action of my NotHome
controller". I purposly put "Not" to illustrate that naming conventions of "Default.aspx", "Index.html" don't apply to MVC routes.
The home page would usually equate to the default action/view on the default controller.
So you'd create, for example, a HomeController
with an Index
action and a corresponding view, then in your route mappings you'd create a default, catch-all route, something like this:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
It depends on what you mean by "home page". If you mean the page seen when you go to http://www.yoursite.com (with no page or Controller name) then that is the Index controller, which works like any other except you don't see the name of the controller in the URL.
精彩评论