ASP. NET MVC3 Series Tutorial – New layout system

Source: Internet
Author: User

Original address: http://www.cnblogs.com/highend/archive/2011/04/18/asp_net_mvc3_layout.html

I: Memories of MVC2 masterpage those things

Code

<!------------Begin--------------><!--Master File --<%@ Master Language= "C #"     Inherits= "System.Web.Mvc.ViewMasterPage"%>master Head<ASP:ContentPlaceHolder ID= "MainContent" runat= "Server" />Master1 ...<ASP:ContentPlaceHolder ID= "Othercontent" runat= "Server" />Master2 ...<ASP:ContentPlaceHolder ID= "Anycontent" runat= "Server" />Master3 ...<!-------------End---------------><!------------Begin--------------><!--A view file-- <%@ Page Language= "C #"     MasterPageFile= "~/views/shared/site.master"     Inherits= "System.Web.Mvc.ViewPage"%><ASP:Content ID= "Content1" ContentPlaceHolderID= "MainContent" runat= "Server" >MainContent ...</ASP:Content><ASP:Content ID= "Content2" ContentPlaceHolderID= "Othercontent" runat= "Server" >Othercontent ...</ASP:Content><ASP:Content ID= "Content3" ContentPlaceHolderID= "Anycontent" runat= "Server" >Anycontent ...</ASP:Content><!-------------end---------------><!------------Begin--------------><!--The last file returned to the client. Master headmaincontent ... Master1 ... Othercontent ... Master2 ... Anycontent ... Master3 ...<!-------------End--------------->

We can see that the ContentPlaceHolder service-side control in master acts as a placeholder. The final output, in fact, is the contents of the Content server control in the view, and then we begin to introduce layout.

II:ASP.NET MVC3 New layout system

In the MVC3 we can use the new layout system to replace the original used in the MVC2 masterpage (of course, in the MVC3, if you continue to use the ASPX view engine, then you can still use the original masterpage, and then ~ ~ ~ Then you will and runat= "server" keep the relationship from. NET 1.x to. NET 4.0 since there is no interruption in the partnership, it is a fate!).

When we create item in the VS2010 MVC3 project, we can see the following new items from the Create wizard

The following are described below:

Layout page:
This guy is actually the equivalent of the original master file. It has made a great contribution to the unified theme interface of the site and the reduction of most of the redundant html,head,body tags. it is not MO! MasterPage his birth was in the. NET 2.0 version! In service to. A new member appeared after the NET4.0 version [Layout] to challenge him. Can the masterpage withstand the challenges of the new members? This still has to be left to the audience to do a detailed comparison!

Partial page:
The equivalent of the original UserControl. It can relieve you a lot of time to repeat work!

View page:
It's the view. When you create it. It is usually when you do not need to use layout/masterpage.

View Page with Layout:
is equivalent to the original view Content Page. Its function is only to implement the placeholder that was originally defined under Layout/masterpage. Of course in the original masterpage if you did not implement the previously defined placeholder <asp: ContentPlaceHolder/>, then the masterpage placeholder <asp:contentplaceholder/> When the final merge output is output empty.

All of these 4 new members are able to work with the new Razor view engine. If you don't know razor, then you can refer to my other article.

1.Layout Page Basics:
If you have experience using MasterPage, you will remember the following several things

a:<%@ Master%>

b:<%@ Page%>

C:<asp:contentplaceholder/>

D:<asp:content/>

But in layout, these things will disappear. (the author does not rule out the possibility of webpages and WebForms compatible work)

Instead, the new features are:

A.layout property: Equivalent to the original MasterPageFile property.

[Email protected] () method: Renders the entire view directly to the placeholder, without needing the original <asp:content/>.

[Email protected] () Method: Renders the specified page at the placeholder.

[Email protected] Method: Declares a placeholder, similar to the original <asp:contentplaceholder/> function.

[email protected] Tag: The placeholder for the @rendersection method declaration is implemented, similar to the original <asp:content/> function.

[Email protected] () Use of the method

First create a layoutpage file named _mylayout.cshtml under ~/views/shared/and replace the default content with the following:

<! DOCTYPE HTML >< HTML >< Head >    < title >@ViewBag title</title></head><  body>    <Div>        Start rendering body<  br/>        @RenderBody ()        render body End <br/>     </div></body></html  >

Then open the ~/views/home/index.cshtml file and replace it with the following:

@{    "Home";} < Div >    This is the rendering body. ~ ~ No need to write God horse &lt; Asp:content/&gt;, in fact, because Renderbody () is not ambiguous. </ Div >

The final output is:

This is a lot less than the amount of code previously masterpage, and more concise and straightforward.

Finally, don't forget to change the layout property in ~/views/_viewstart.cshtml to:

Layout = "~/views/shared/_mylayout.cshtml"; Oh.

Here, you may have doubts. The renderbody () defined in _layout is the render page?

A: In fact, the final render page belongs to the page you visited, such as your visit to/home/index. Then render is the Home controller index.cshtml This file, if the access is/ohter/somepage, So the render is the somepage under the Ohter controller. cshtml!

There may be friends here who have not been exposed to MVC. This complements the base, under the Default Routing settings option:

 Public Static void RegisterRoutes (routecollection routes) {    routes. Ignoreroute ("{resource}.axd/{*pathinfo}");    Routes. MapRoute (        "Default"//Route name        "{controller}/{action}/{id}"//URL With parameters        new"Home""Index"urlparameter// Parameter defaults    );}

Request Address: Http://localhost/Home/Index's workflow is (layout not considered here):

If this renderbody does not satisfy your business needs, please be assured that another render mode Renderpage () is introduced here. It lets you specify the page to render.

[Email protected] () Use of the method

Create a new viewpage1.cshtml file under the ~/views/home/folder and change the content to read as follows:

< Div >    This is ~/views/home/viewpage1.cshtml, the usual: or do not write &lt; Asp:content/&gt; </ Div >

and add a few lines of code to the original _mylayout.cshtml file to look like this:

  <!   DOCTYPE   HTML   ><   HTML   ><   Head     ;   <   title  ;  @ViewBag. Title  </  Title   ></  head   ><   Body     ;   <   Div  ;  start rendering Body  <   br  />  @RenderBody () render body End span><   br  />   <   br  />  start rendering its        He page  <   br  />  @RenderPage ( "~/views/home/viewpage1.cshtml" ) Render other pages end  <   br  />   </  div   >< /  body   ></  html  ;  

Let's look at the final output effect:

Remember here: @RenderBody () can only be used once in _layout.cshtml, while @renderpage () is available multiple times!

Well, if there are any friends here who don't understand. I have a diagram below that shows how render works

If you want to know how to use the <asp:contentplaceholder/><asp:content/> feature in layout similar to the original masterpage, continue looking down.

III: Implementation similar to the original MasterPage function in Layout system

Well, here's the two things that are not covered in the previous section: @RenderSection Methods and @section tags
[Email protected] The () method is equivalent to <asp:contentplaceholder/>, and is used to declare a placeholder in layout.
Action: Change the contents in the original _mylayout.cshtml file as follows:

@{//some Code}<!DOCTYPE HTML><HTML><Head>    <title>@ViewBag. Title</title></Head><Body>    <Div>Start Rendering Body<BR />@RenderBody () Render body End<BR />        <BR />Start rendering other pages<BR />@RenderPage ("~/views/home/viewpage1.cshtml"Render Other pages end<BR />        <BR />HOHO, start studying section.<BR />Start Rendering Section<BR />Declaration Method 1 (recommended): Sectiona:<BR />@RenderSection ("Sectiona",false)        -------<BR />Declaration Method 2:sectionb:<BR />@{if(Issectiondefined ("Sectionb") {@RenderSection ("Sectionb")            }        }        -------<BR />Render Sction End<BR />    </Div></Body></HTML>

In ~/views/home/index.cshtml, change to the following:

@{    "Home";            //    //Some code    //} @section sectiona{    <Div> here is Sectiona: Also do not need to write God horse runat= "Server" Ah, there are wood  </div>} @section sectionb{    <Div> This is sectionb: no need to write God horse &lt; Asp:content/&gt Ah, there's wood there </div>}<Div>     This is the rendering body. ~ ~ No need to write God horse &lt; Asp:content/&gt;, in fact, because Renderbody () is not ambiguous. </ Div >

Last displayed page effect:





Q: Why should I recommend mode 1?

Answer: Because the Rendersection () method has 2 overloads.

If you use the first overload that accepts only one parameter of type string. ~ If you do not use @section to define the implementation in the specific view, the operation will be error-free. So it is necessary to use another method issectiondefined () to prevent error.

Using the 2nd overload, you can use the parameter of the second bool type to indicate whether the section is required. So you can use the Rendersection method directly with the second overload, and then set the bool parameter value to False, Even if you do not declare in the specific view of the implementation of @section, running up as always, the egg set, not show Yellow pages.

IV: Questions about how to read the database and initialize the page in Layout (MasterPage) with enthusiastic viewers in the previous article

Here is just a simple demonstration, create a new class file, replace the following:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Data;usingSystem.Data.SqlClient;//Use the ADO method here. EF I'm in touch soon!namespacemvc3application1{ Public class readersql_date{Private Static ReadOnly string_sql_conn_str ="server=.\\mssqlserver,1433;uid=sa;pwd=yourpwd;database=student;"; Public Static IList<studententity> Getallstudent () {//Here is just a demonstration, the production environment does not write this            using(SqlConnectionconn =New SqlConnection(_SQL_CONN_STR)) {SqlCommandCMD = conn.                CreateCommand (); Cmd.commandtype =CommandType.                Text; Cmd.commandtext ="SELECT [Sno],[sname],[sage] FROM [dbo]. [STUDENT] ";IList<studententity> result =New List<studententity> (); Conn. Open ();using(SqlDataReaderSDR = cmd. ExecuteReader ()) { while(SDR). Read ()) {result. ADD (New studententity{s_no = SDR. GetInt32 (0), S_name = SDR. GetString (1), S_age = SDR.                    GetInt32 (2)}); }                }//sqlconnection.clearpool (conn);//optional Cleanup connection pool.                returnResult }        }    } Public class studententity{ Public intS_No {Get;Set; } Public stringS_name {Get;Set; } Public intS_age {Get;Set; }    }}

The _mylayout.cshtml is replaced as follows:

@{IList<mvc3application1.studententity> studententities = mvc3application1.readersql_date. Getallstudent ();}<!DOCTYPE HTML><HTML><Head>    <title>@ViewBag. Title</title></Head><Body>    <Div>@{<Table>                <TR>                    <th>School Number</th>                    <th>Name</th>                    <th>Age</th>                </TR>@foreach(Mvc3application1.studententityIteminchStudententities) {<TR>                        <TD>@item. S_No</TD>                        <TD>@item. S_name</TD>                        <TD>@item. S_age</TD>                    </TR>}</Table>} Starts rendering body<BR />@RenderBody () Render body End<BR />        <BR />Start rendering other pages<BR />@RenderPage ("~/views/home/viewpage1.cshtml"Render Other pages end<BR />        <BR />HOHO, start studying section.<BR />Start Rendering Section<BR />Declaration Method 1 (recommended): Sectiona:<BR />@RenderSection ("Sectiona",false)        -------<BR />Declaration Method 2:sectionb:<BR />@{if(Issectiondefined ("Sectionb") {@RenderSection ("Sectionb")            }        }        -------<BR />Render Sction End<BR />    </Div></Body></HTML>

Final display:

This is the end of the article!
Thank you for your interest in this series of tutorials and followers of bloggers! There are people who [recommend] I will have the power to write this series down!

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.