In-depth analysis of viewengine and Application Instances

Source: Internet
Author: User
ArticleDirectory
    • Iview Interface
    • Iviewengine Interface
    • Viewengineresult
    • Viewenginecollection
    • 1. Implement the iview Interface
    • 2. Implement the iviewengine Interface
    • 3. Use stringtemplateviewengine
I. Summary

This article explains the role of viewengine, deeply parses all the interfaces and classes related to viewengine implementation, and finally demonstrates how to develop a custom viewengine. all articles in this series have been updated to ASP. net MVC 1.0. I hope you will have more support!

Ii. Connecting

First of all, note that the ASP. NET page programming model that has been used before MVC is called the ASP. NET webform programming model.

In the previous lecture, we learned how to pass the model to the view and how to use the model object in the view. so far we are still using ASP. net webform page model, such as ASPX page, user control, master page, etc. finally, these pages must be converted to HTMLCodeFor example, embedded code in the page:

 
<%= Viewdata ["Model"]%>

Have you ever thought about why the page supports<%>This syntax? Why is the last ASPX page displayed in the browser in the form of HTML code?

Someone will reply that this is ASP. net built-in syntax and functions. no error, Asp. net helped us compile pages, output HTML, and return HTML to the client browser. however, many of these jobs belong to the view role in the MVC framework. to continue using the original ASP. net webform page engine, Asp. net MVC abstracts the role of viewengine. as the name suggests, viewengine is the view engine. Its main function is to find the view object, compile the language code in the view object (execute the Language Logic), and output HTML. the webformviewengine described below uses ASP. net webform page compilation/rendering function.

3. viewengine Parsing

The following describes various viewengine-related interfaces and classes.

Iview Interface

The iview interface is an abstraction of the view object in the MVC structure. This interface has only one method:

 
VoidRender (viewcontext, textwriter writer );

The render method is used to display the view object. Generally, the HTML of the page is written to the writer for display by the browser.

In the third article of this series, I have analyzed that although the iview object is the abstract of the view role in MVC, and provides the render method, however, the display logic of the real view role is in the viewpage/viewusercontrol class. this is because ASP. net MVC provides the webformviewengine view engine that uses the original ASP. net web from page display mechanism, we cannot directly convert the pages in the webform model into iview objects.

So we finally used a compromise:

In the render method of the iview object, the render method of the webform page is called. webformview is the only class in ASP. net mvc that implements the iview interface.

Therefore, if we use a custom viewengine, we can directly create a class that implements the iview interface to implement the render method.

Iviewengine Interface

Viewengine is the view engine. in ASP. net mvc, the role of viewengine is abstracted into an iviewengine interface.

Although iviewengine is responsible for finding view objects, it defines two methods:

    • Findpartialview
    • Findview

The returned result is a viewengineresult object, which is not a view object. we can regard viewengineresult as the result of a query. The viewengineresult object contains the iview object found this time.

ASP. net mvc provides the following two classes that implement the iviewengine interface:

    • Virtualpathproviderviewengine
    • Webformviewengine

Webformviewengine is a derived class of virtualpathproviderviewengine.

The virtualpathproviderviewengine class implements the findpartialview/findview method, which allows you to search for page files based on the specified path format and cache data. note that ASP is used.. Net cache depends on the httpcontext object, which causes the cache to be unavailable in projects such as WebService or WCF. the virtualpathproviderviewengine Method for searching pages depends on the following three attributes:

    • Masterlocationformats
    • Viewlocationformats
    • Partialviewlocationformats

Only these three attributes are defined in virtualpathproviderviewengine. The specific value is specified in the derived class webformviewengine:

Public webformviewengine () {<br/> masterlocationformats = new [] {<br/> "~ /Views/{1}/{0}. Master ", <br/> "~ /Views/shared/{0}. Master "<br/>}; <br/> viewlocationformats = new [] {<br/> "~ /Views/{1}/{0}. aspx ", <br/> "~ /Views/{1}/{0}. ascx ", <br/> "~ /Views/shared/{0}. aspx ", <br/> "~ /Views/shared/{0}. ascx "<br/>}; <br/> partialviewlocationformats = viewlocationformats; <br/>}

In the above code, we can search for all the paths in the render viewengine step by step. We can even add our own paths and file types.

With the virtualpathproviderviewengine class, you do not need to write the logic for searching view files when developing custom viewengine. you only need to define the search path. if you do not use ASP. net webform, You need to define how the view object is displayed and finally converted to HTML code.

The following example shows how to create a custom viewengine.

Viewengineresult

Viewengineresult is the query result of viewengine looking for a view. The viewengineresult class does not have a derived class, that is, the results returned by different viewengines are all viewengineresult objects.

The viewengineresult class has a very important constructor:

 
PublicViewengineresult (iview view, iviewengine viewengine)

Taking webformviewengine as an example, masterlocationformats/viewlocationformats/partialviewlocationformats is defined in the webformviewengine class. When the findpartialview/findview method is called, the disk path of the view object is first found, then, use the createpartialview/createview method to convert the disk path to a webformview object that implements the iview interface.

The disk path of the page object is still saved in webformview. When calling render, The viewpage object is created based on the disk path and the render method of the page is called. ASP. net MVC is used to compile the page. net Framework 2.0 or a later version provides functions for compiling pages based on virtual paths:

 
Buildmanager. createinstancefromvirtualpath (StringVirtualpath, type requiredbasetype)

The namespace is system. Web. compilation.

Viewenginecollection

viewenginecollection is a collection class of iviewengine objects. multiple viewengines can be used in our system. When searching, the first matching viewengineresult will be returned. The following is the find method code of the viewenginecollection class:

Private synchronized find (func <iviewengine, viewengineresult> cachelocator, func <iviewengine, viewengineresult> Locator) {<br/> viewengineresult result; <br/> foreach (iviewengine in items) {<br/> If (engine! = NULL) {<br/> result = cachelocator (engine); <br/> If (result. view! = NULL) {<br/> return result; <br/>}< br/> List <string> searched = new list <string> (); <br/> foreach (iviewengine engine in items) {<br/> If (engine! = NULL) {<br/> result = Locator (engine); <br/> If (result. view! = NULL) {<br/> return result; <br/>}< br/> searched. addrange (result. searchedlocations); <br/>}< br/> return New viewengineresult (searched); <br/>}

Through the code above, we learned that viewenginecollection will first search from the cache. If no results are found, it will be searched based on the path format. if no view object is found at the end, an exception is thrown.So although we can add multiple viewengines, never specify the same search format (path + file type) for two viewengines ), if a Page Object matches the search format of two viewengines, you cannot control which viewengine output page to use.

InViewbaseresult. executeresult ()The viewenginecollection. Find method is called to obtain the viewengineresult object, and the iview. Render () method is called to display the view object.

4. develop custom viewengine

The following example shows how to develop your own viewengine. the stringtemplate template engine is used to demonstrate viewengine in Lao Zhao's MVC video tutorial. stringtemplate is responsible for translating placeholders on a template page (embedded code in the ASPX page) and outputting HTML. currently, the official website of stringtemplate has provided. net MVC viewengine. however, the official viewengine template does not use the virtualpathproviderviewengine base class. below I will provide a stringtemplateviewengine that cannot be better but at least is another implementation. the stringtemplate template function is required.

1. Implement the iview Interface

To develop a viewengine, first create a class that implements the iview interface. Here we create a class named stringtemplateview.

Public class stringtemplateview: iview <br/>{< br/> # region properties <br/> /// <summary> <br/> // stringtemplate object, create <br/> /// </Summary> <br/> private stringtemplate <br/>{< br/> get; set; In the constructor; <br/>}< br/> # endregion <br/> # Region constructed function <br/> private stringtemplateview () <br/>{< br/> // This. stringtemplate = new stringtemplate (); <br/>}< br/> Public stringtemplateview (stringtemplate template) <br/>{< br/> // null check <br/> If (template = NULL) throw new argumentnullexception ("template "); <br/> // set template <br/> This. stringtemplate = template; <br/>}< br/> # endregion <br/> # region iview member <br/> void iview. render (viewcontext, system. io. textwriter writer) <br/>{< br/> foreach (VAR item in viewcontext. viewdata) <br/>{< br/> This. stringtemplate. setattribute (item. key. tostring (), item. value. tostring (); <br/>}< br/> // set httpcontext for stringtemplate <br/> This. stringtemplate. setattribute ("context", viewcontext. httpcontext); <br/> // output template <br/> noindentwriter = new noindentwriter (writer); <br/> This. stringtemplate. write (noindentwriter); <br/>}< br/> # endregion <br/>}

Stringtemplateview is the abstract of the view role in the stringtemplate view engine, so the function is to render the page render method. the core function of stringtemplate is a set of Custom template output engines. Therefore, when constructing a stringtemplateview object, you must pass in a stringtemplate instance. In render, you only call the template output method of the stringtemplate object.

2. Implement the iviewengine Interface

With the iview object, we need to implement the core iviewengine interface. In the specific stringtemplateviewengine class, we need to return a viewengineresult with the stringtemplateview object.

In my implementation method, I used the virtualpathproviderviewengine class provided by ASP. NET MVC as our base class. virtualpathproviderviewengine class to implement the iviewengine interface method.ProgramTo search for the physical file path of the view, you must use the search path assigned in the derived class.

The following is the implementation of our stringtemplateviewengine class:

Public class stringtemplateviewengine: virtualpathproviderviewengine <br/>{< br/> private string _ apppath = string. empty; <br/> # region properties <br/> Public static filesystemtemplateloader loader {Get; private set ;}< br/> Public static stringtemplategroup Group {Get; private set ;} <br/> # endregion <br/> Public stringtemplateviewengine (string apppath) <br/>{< br/> _ apppath = apppath; <br/> loader = new filesystemtemplateloader (apppath); <br/> group = new stringtemplategroup ("views", loader ); <br/> masterlocationformats = new [] {<br/> "/views/{1}/{0 }. st ", <br/>"/views // shared/{0 }. st "<br/>}; <br/> viewlocationformats = masterlocationformats; <br/> partialviewlocationformats = masterlocationformats; <br/>}< br/> protected override iview createpartialview (controllercontext, string partialpath) <br/>{ <br/> return this. createview (controllercontext, partialpath, String. empty); <br/>}< br/> protected override iview createview (controllercontext, string viewpath, string masterpath) <br/>{< br/> stringtemplate = group. getinstanceof (viewpath. replace (". st "," "); <br/> stringtemplateview result = new stringtemplateview (stringtemplate); <br/> return result; <br/>}< br/>}

Note: In our stringtemplateviewengine, the path of the template file is provided, that is, the path is searched from view/{controller} And then from view/share. in this way, we can find the virtualpathproviderviewengine base class method. the path of the St template file. Then, use the method provided in stringtemplateviewengine to create the stringtemplateview object.

In some open-source viewengines, especially in the mvccontrib project, viewengine puts the function of creating a view object in a viewfactory class. I personally think this is a better design, however, because our stringtemplateviewengine inherits virtualpathproviderviewengine, there is no way to split the view creation method.

Now we have completed all the work of stringtemplateviewengine.

3. Use stringtemplateviewengine (1) to add SMART awareness to the. St template page

First, make some preparations. because our stringtemplate file suffix is ". st ", most of the code written in it is HTML code. by default, Visual Studio is not edited. smart sensing is supported when the st function is used. however, you can use the following settings:

Click "Tools"-> "options" in the menu ":

In the file extension of "Text Editor", add "HTML editor" for the. St extension ".

Next, you can identify the HTML code in the. St file:

(2) create a common menu Template

The stringtemplate engine supports template nesting. Therefore, you can set the common menu bar of two pages to menu. in the st file. in addition, we put this file in the share folder for calling on all template pages. menu. the St file code is as follows:

 <  Ul   ID  = "Menu"  > 
< Li > < A Href = "/Stringtemplate/hellost" > Hellost </ A > </ Li >
< Li > < A Href = "/Stringtemplate/sharedst" > Sharedst </ A > </ Li > </ Ul >
(3) create a Page Template and Controller

In the Controller folder, create stringtemplatecontroller to jump to our template page:

Public class stringtemplatecontroller: controller <br/>{< br/> Public actionresult hellost () <br/>{< br/> viewdata ["MSG"] = "Hello string template! "; <Br/> return view (" hellost "); <br/>}< br/>}

Create a stringtemplate folder in the view folder and add a hellost. St file:

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 strict // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <br/> <HTML xmlns = "http://www.w3.org/1999/xhtml"> <br/> <pead> <br/> <title> st page in the shared folder </title> <br/> <link href = ".. /content/site.css "mce_href =" content/site.css "rel =" stylesheet "type =" text/CSS "/> </pead> <br/> <body> <br/> <Div class = "page"> <br/> <p> stringtemplateviewengine sample program </p> <br/> <Div id = "menucontainer"> <br/> $ views/shared/menu () $ <br/> </div> </P> <p> <Div id = "Main"> <br/> $ MSG $ <br/> </div> <br/> </div> <br/> </body> <br/> </ptml>

The code in the example is very simple. "$ MSG $" is the template language of stringtemplate and can recognize variables named "MSG. "$ views/shared/menu () $" is also the syntax in stringtemplate. It loads a template named menu.

(4) load the stringtemplateviewengine template engine

Although the controller and view files have been created. net MVC default view engine is webformviewengine, but multiple view engines can be used at the same time, for example, all ". the St "suffix file uses the stringtemplateviewengine view engine. in global. in the asax file, register our viewengine when the program starts:

Protected void application_start () <br/>{< br/> registerroutes (routetable. routes); <br/> // Add the stringtemplate view engine <br/> stringtemplateviewengine engine = new stringtemplateviewengine (server. mappath ("/"); <br/> viewengines. engines. add (engine); <br/>}

V. Introduction to other viewengine

In addition to self-developed viewengine, many viewengines for ASP. net mvc are available:

Viewengine in the mvccontrib project:

    • Sparkviewengine (not recommended)
    • Brailviewengine
    • Xsltviewengine

Stringtemplateviewengine

This is the viewengine developed by the stringtemplate project for ASP. net mvc. The official and download URL is

Http://www.stringtemplate.org/

In addition, there are some page display engines similar to stringtemplate in the famous monorail project, although they are not ASP. net MVC develops specialized viewengine, but it is of great reference value. we can use the method described above to Develop ASP Based on the page display engine. net MVC viewengine:

Three viewengines In the monorail project:

    • Aspnetviewengine: traditional. the aspx file can be used as a template, And the aspx syntax and server control can be used as usual. However, because the lifecycle of the webform is completely different from that of monorail, it is sometimes awkward and some features are restricted.
    • Nvelocityviewengine: nvelocity is used as a template engine. You need to learn VTL syntax, but it is easy to use. In particular, many Java programmers are familiar with velocity. simple syntax also forces programmers to separate the logic from the interface to facilitate cooperation with the artist.
    • Brailviewengine: Boo-based template engine. Boo is a syntax similar to Python. net Language, according to monorail reference, Brail engine is the most powerful, the best choice for performance, but Boo is a strange language, which has become the biggest obstacle to Brail engine application.
Vi. Summary

This article describes in detail the related classes of viewengine and how to develop your own viewengine. it took two weeks to complete the creation, which made everyone wait. speaking of my recent blog post on the homepage, I think an article should be well explained in addition to knowledge points, so that you can understand it more important than understanding it yourself. I didn't post articles for speed. I just wanted to write something that could be posted on the blog homepage.

I hope that everyone will build a blog park through self-discipline and understand that sharing knowledge is a glorious and happy thing!

Download sample code:

Http://files.cnblogs.com/zhangziqiu/AspNetMvc-5-Demo.rar

From: http://blog.csdn.net/study_live/archive/2009/11/20/4841839.aspx

 

 

You can easily understand the UML:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.