Display only this paper let you understand View ASP.NET MVC's (only this paper s

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Digression

A week before writing "only in this paper allows you to understand the principle of ASP.NET MVC" by the majority of ASP.NET learning MVC students welcome, so determined to turn it into a series, to meet the more hungry for knowledge of the students. Mr. Jiang Jinnan has been in his "ASP.NET MVC 4" frame secret book have explained it very deeply. I can't put his paper down to you. Then we might as well look at his blog. I want to do is to provide based graphical, intuitive, simple system, the understanding of . Part of the contents to understand students, or spend some money to buy a copy of his book, very worth a visit (no advertising⊙﹏⊙‖∣).

Some people to question, why do I have to learn the framework? Here I simply said once, in-depth understanding of a frame, the most direct benefits to you:

  1. Using the framework, problems can quickly locate, and know how to solve,
  2. When some function framework with the spreadsheet, you can be free to expand, to achieve what you want to do, or can get the source directly modify,
  3. The only way which must be passed to be framework division,
  4. Extraction in the framework of good code and ideas, for their own use,

More good, you can go to experience, are interested can look at the asp.net MVC part of the source code:

The purpose of this paper

An article is to let you understand two processes of the core of MVC (if you haven't seen please click here, only delay your nap a few minutes). We then the method from InvokeAction ControllerActionInvoker executive Action speaking:

//Implementation of Action, and ActionResult
    ActionResult actionResult = method.Invoke(controllerContext.Controller,
        parameters.ToArray()) as ActionResult;

    //The final ActionResult HttpResponse returns data to the customer display
    actionResult.ExecuteResult(controllerContext);

The purpose of this paper is to let you understand this code do what? MVC Controller how to find View, and display.

Begin the journey

On the class diagram and the related:

http://www.cnblogs.com/DotCpp/

This graph looks like structure is quite complex, but in fact he is very simple, give me two minutes, I will let you know what is this shit, what is the relationship between?

ActionResult said that the first, from the chart to see, ActionResult is an abstract class, there are a lot of, his sub classes such as JsonResult, ContentResult, ViewResult, EmptyResult etc.. The things we use MVC often contact, such as:

public class HomeController:Controller
{
    public ActionResult Index()
    {
         return View();
    }

    public ActionResult GetInfo()
    {
         ...
        return Json(obj);
     }
 
     public ActionResult GetContent()
     {
         return Content("test");
      }
}

The above three Action return respectively corresponding to ViewResult, JsonResult, ContentResult, and I figure painting only ViewResult, because it is a ActionResult we use the most, but is one of the most complex (due to the display for View). And have a look ContentResult the core source code, I simply want to everyone laugh:

public class ContentResult : ActionResult
    {
        public string Content { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;
            
            if (Content != null)
            {
                response.Write(Content);
            }
        }
    }

Realization and above its structure picture I drew no half cents relationship, directly to a Response.Write output is finished. So I use ViewResult to write the paper.

The next note ViewEngines the static class, look at its source:

 public static class ViewEngines
    {
        private static readonly ViewEngineCollection _engines = new ViewEngineCollection
        {
            new WebFormViewEngine(),
            new RazorViewEngine(),
        };

        public static ViewEngineCollection Engines
        {
            get { return _engines; }
        }
    }

Only a static read-only members of type ViewEngineCollection, the initialization package two view engine, WebFormViewEngine and RazorViewEngine? The two is what? In order to understand this, we have a look the RazorViewEngine source code (WebFormViewEngine are basically the same, the length limit below I use Razor for example):

public class RazorViewEngine : BuildManagerViewEngine
    {
        internal static readonly string ViewStartFileName = "_ViewStart"; //Storage of ViewStart template

        public RazorViewEngine(IViewPageActivator viewPageActivator)
            : base(viewPageActivator)
        {
           //These structures we should feel very warm
            ViewLocationFormats = new[]
            {
                "~/Views/{1}/{0}.cshtml",
                "~/Views/{1}/{0}.vbhtml",
                "~/Views/Shared/{0}.cshtml",
                "~/Views/Shared/{0}.vbhtml"
            };
            MasterLocationFormats = new[]
            {
                "~/Views/{1}/{0}.cshtml",
                "~/Views/{1}/{0}.vbhtml",
                "~/Views/Shared/{0}.cshtml",
                "~/Views/Shared/{0}.vbhtml"
            };
            PartialViewLocationFormats = new[]
            {
                "~/Views/{1}/{0}.cshtml",
                "~/Views/{1}/{0}.vbhtml",
                "~/Views/Shared/{0}.cshtml",
                "~/Views/Shared/{0}.vbhtml"
            };

            FileExtensions = new[]
            {
                "cshtml",
                "vbhtml",
            };
        }


        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            var view = new RazorView(controllerContext, viewPath,
                                     layoutPath: masterPath, runViewStartPages: true, viewStartFileExtensions: FileExtensions, viewPageActivator: ViewPageActivator)
            {
                DisplayModeProvider = DisplayModeProvider
            };
            return view;
        }
    }

As you can see from the code, RazorViewEngine just package the View file path. I'll explain how they are used.

Know the basic situation of above a few classes, a look at the implementation process, the functions of each class you will have a general understanding, ExecuteResult and executes when the controller Action returns a ViewResult (when this paper introduces code):

  1. Obtain the ViewResultEngine object from the ViewEngines Engines, Essence is to traverse the RazorViewEngine and WebFormViewEngine, And then through the member function FindView their inheritance in VirtualPathProviderViewEngine to create ViewResultEngine [from the timing diagram below that, Although the MVC to hide this thing very deep, But the basic is transmitted in the parent class and sub class, The structure is clear],
  2. The ViewResultEngine obtained through the View executive Render interface display, internal calls the RazorView RenderView to display the final,

The core process is above two, the execution sequence diagram as shown below (click the image for a larger view):


http://www.cnblogs.com/DotCpp/

 Now pay attention to seventeenth step process, namely the executive Render BuildManagerCompliedView function, this function is the soul of View display:

        public virtual void Render(ViewContext viewContext, TextWriter writer)
        {
            object instance = null;
            
            //The ViewPath is based on View specific path RazorViewEngine template position is obtained, created in RazorViewEngine ViewEngineResult came in.
            Type type = BuildManager.GetCompiledType(ViewPath);
            if (type != null)
            {
                instance = ViewPageActivator.Create(_controllerContext, type);
            }

            if (instance == null)
            {
                throw new InvalidOperationException(
                    String.Format(
                        CultureInfo.CurrentCulture,
                        MvcResources.CshtmlView_ViewCouldNotBeCreated,
                        ViewPath));
            }

            RenderView(viewContext, writer, instance);
        }

According to the above instance ViewPath generated is what? Have a look in the implementation of RazorView RendView will know:

 protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)
        {
            WebViewPage webViewPage = instance as WebViewPage;
            //Other code regardless of
            webViewPage.ExecutePageHierarchy(new WebPageContext(context: viewContext.HttpContext, page: null, model: null), writer, startPage);
        }

Is the original object WebViewPage, check out MSDN knew, all View are from the generic WebViewPage< WebViewPage; TMode> direct inheritance. We take a look at this class:

    public abstract class WebViewPage : WebPageBase, IViewDataContainer, IViewStartPageChild
    {
        private ViewDataDictionary _viewData;
        private DynamicViewDataDictionary _dynamicViewData;

        public AjaxHelper<object> Ajax { get; set; }
        public HtmlHelper<object> Html { get; set; }

        public object Model
        {
            get { return ViewData.Model; }
        }

        public TempDataDictionary TempData
        {
            get { return ViewContext.TempData; }
        }

        public UrlHelper Url { get; set; }

        public dynamic ViewBag
        {
            get
            {
                if (_dynamicViewData == null)
                {
                    _dynamicViewData = new DynamicViewDataDictionary(() => ViewData);
                }
                return _dynamicViewData;
            }
        }

        public ViewContext ViewContext { get; set; }

        public override void ExecutePageHierarchy()
        {
              Execute();  //This function is defined in the base class function, will generate in the final aspx/cshtml class is overloaded
        }

        public virtual void InitHelpers()
        {
            Ajax = new AjaxHelper<object>(ViewContext, this);
            Html = new HtmlHelper<object>(ViewContext, this);
            Url = new UrlHelper(ViewContext.RequestContext);
        }
    }

      Is it right? Where we saw a lot of property is usually the most commonly used. When using the ExecutePageHierarchy when the page is generated, the actual calls the Execute function, this function will be in the final cshtml, ASPX etc. the generated class is overloaded. We look at a simple example:

Suppose we have a strongly typed view: /Views/Home/Index.cshtml, a simple DemoModel type, only one UserName attribute:

@model Controllers.DemoModel
<div>Index</div>
@Model.UserName

Then the Index.cshtml is compiled will generate the following categories:

public class _Page_Views_Home_Index_cshtml : WebViewPage<DemoModel>
{
    public override void Execute()
    {
          this.WriteLiteral("<div>Index</div");
          this.Write(Model.UserName);
    }
}

Thus, the WEB display.

Postscript

The thought of this article is well written, unexpectedly and wrote two days. Or that sentence: Hope novice see understand, veteran more suggestions, thank you!

The next article will release an important part of View display: Model Data on the (don't you look not think less of something? Talk about the process, how the actual data transfer? How to display?) Attention, please!


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Cornell at November 13, 2013 - 4:12 PM