简体   繁体   中英

ASP.Net MVC Controller and View interaction

I created a sample MVC application using following Template.

ASP.NET MVC2 Empty Web Application

Then a added a Controller with the name of First and a right clicked the ActionResult to add a View .

I typed http://localhost:49565/First in my Browser.

Query

How is the controller internally getting to know that a specific page will be displayed when we will type http://localhost:49565/First ?

Moreover, If I add multiple Views for a Controller . How will the system decide which one will be displayed on Priority ?

The controller is invoked by the MVC framework, which uses the routes defined in Global.asax.cs to determine which controller and action to invoke. There is a default route that looks like this:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

When the application receives a request is will try to parse the URL to the format of the routes. If the request is made to http://localhost:49565/ , it will use the default values which goes to the Index action in the controller named HomeController . When you have created the new controller, FirstController , and call http://localhost:49565/First , it uses the FirstController instead of the HomeController since it has been provided (but still to the Index action).

Further, when an action is being invoked and there is no view defined explicitly, it will look for a view named the same as the invoked action. In your case it would be ~/Views/First/Index.aspx .

EDIT

If you want to use another view you can specify it in the return statement

return View("OtherView");

and it will use ~/Views/First/OtherView.aspx instead.

看看这个博客文章,让您知道如何完成

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM