The role of the action method in the controller is to return an ActionResult,which often is ViewResult.The ViewResult is rendered by the ViewEngine so that the user is returned HTML or other appropriate response.
Some of the important components involved in processing the ActionResult and rendering the result are
- ViewResult
- ViewEngineResult
- IViewEngine
- IView
ViewResult is returned by the action method which is processed by the ViewEngine.ViewEgine contains a method FindView and FindPartialView which returns a ViewEngineResult object.
ViewEngineResult contains references to IView and IViewEngine .Once the ViewEngineResult object is returned by the FindView() method ,IView implementation,such as razor , contains a render method which generates the response for the requested view.
If we are using the built in ViewEngine like razor then above tasks are handled automatically so we don’t need to be concerned about the above details.
Please note that if we are using razor view engine then the View is compiled .This means that a class is generated from the view which executes to return the response to the user.This class is generated when the view is requested. The name of this class is generated by concatenating the name of the view and the location of the view.So if the name of the view is Index then the name of this generated view class will be
_Page_Views_Home_Index_cshtml
This class contains an Execute method which contains the code to generate the appropriate HTML or other response.
Below is the execute method defined in the auto generated class
public class _Page_Views_Home_Index_cshtml : System.Web.Mvc.WebViewPage<List<Employee.Models.EmployeeDetails>> {
public _Page_Views_Home_Index_cshtml() {
}
protected ASP.global_asax ApplicationInstance {
get {
return ((ASP.global_asax)(Context.ApplicationInstance));
}
}
public override void Execute() {
WriteLiteral(“rn”);
ViewBag.Title = “Index”;
WriteLiteral(“rnrn<h2>Index</h2>rn rn {“);
The code that is in the view is converted into WriteLiteral methods in this class.
So our view is converted into a class at runtime and it is this class that generates the appropriate response.
One of the important methods in this request processing is the FindView method.This is the method that searches for the View name passed in different locations.It uses conventions to search for the views.So it searches for the view in the Views/Controller folder and the Views/Shared folder.
Leave a Reply