I have opened a sample ASP.NET MVC project.
In HomeController
I have created a method (action) named MethodA
public ActionResult MethodA() { return View(); }
I have right clicked on MethodA
and created a new view called MethodA1
Re-did it and created a new view called MethodA2
.
How is this magical relationship done? I looked for the config to tell the compiler that views MethodAX
are related to action MethodA
, but found none.
What view will the controller return when MethodA
is called?
The following illustrates the Index() action method in the StudentController class. As you can see in the above figure, the Index() method is public, and it returns the ActionResult using the View() method. The View() method is defined in the Controller base class, which returns the appropriate ActionResult .
The convention is that if you don't specify a view name, the corresponding view will be the name of the action. So:
public ActionResult MethodA() { return View(); }
will render ~/Views/ControllerName/MethodA.cshtml
.
But you could also specify a view name:
public ActionResult MethodA() { return View("FooBar"); }
and now the ~/Views/ControllerName/FooBar.cshtml
view will be rendered.
Or you could even specify a fully qualified view name which is not inside the views folder of the current controller:
public ActionResult MethodA() { return View("~/Views/Foo/Baz.cshtml"); }
Now obviously all this assumes Razor as view engine. If you are using WebForms, replace .cshtml
with .aspx
or .ascx
(if you are working with partials).
For example if there is no view it will even tell you where and in what order is looking for views:
Remember: ASP.NET MVC is all about convention over configuration.
The MVC framework use convention over configuration. The framework calls the ExecuteResult on the ViewResult object (created by the return View();). The framework by convention then looks in a number of locations to find a view
If you are using areas the framework will look in the following locations for a view.
Without areas (or if you are using areas and no view has been found) the framework will look at the following locations
As soon as the Framework tests a location and finds a file, then the search stops, and the view that has been found is used to render the response to the client.
There are a number of overriden versions of the View method. The most common one is to render a specific view, outside of the framework convention, by calling it by name. For example
return View("~/Views/AnotherIndex.cshtml");
As an interesting footnote, the framework looks for legacy ASP, C# and VB Razor views (aspx, ascx, cshtml and vbhtml) even though you have a specific view engine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With