Common code for the ASP. NET MVC View

Source: Internet
Author: User

first, the public template

Transferred from: http://www.cnblogs.com/kissdodog/archive/2013/01/07/2848881.html

 1, @RenderBody ()

In the common section of the site, a placeholder @renderbody () is reserved for a site-independent section. The public template is then introduced at the top of the private page through the @{layout= "Common template Path"}, where it is placed in the public template itself. You can also set ViewData or ViewBag to set the website title, keywords and other information.

@{    Layout = "~/views/shared/_layout.cshtml";    Viewbag.title = "Site title can be set from here";
<!DOCTYPE html><Html><Head><Title> @ViewBag title</title></head><body> < Div> Below is the private part of the page </div> @RenderBody ()</body></ HTML>                  

This introduces the other parts of the common page, and also sets the title.

Second, section-festival

Section:@section

You can set up multiple common template sections by adding sections to the page.

  @RenderSection ("Footer") defines a section that will error when the view does not provide code for this section: The section is undefined: "xxxxxx".

  @RenderSection ("Footer", false) overloads, if the second argument is set to False, then this section is not required and will not be an error when the view does not provide the code for this section.

The following shows a footer section, the following is a public page template

<!DOCTYPE html><Html><Head><Title> @ViewBag. Title</Title></Head><Body><Div> Below is the private section of the page</Div> @RenderBody () @*<> @RenderSection ("footer") </footer>*@//If the second parameter is not set, the error will be prompted if the view does not have a section set. <footer>@ Rendersection ("Footer", false) </footer>//If the second parameter is set to Flase, then the view can either set a section or not set the section. </body></html> 

This is the view.

@{    Layout = "~/views/shared/_layout.cshtml";    Viewbag.title = "Set top caption"; Are you all right in your hometown? @section footer{    This is the footer section}

This is the entire page that will contain the common template, the body and the footer section.

When multiple pages of the page are used in the same layout, each page is assigned its layout through the Layouts property, resulting in redundancy, _viewstart.cshtml can be used to eliminate this redundancy, in the views directory another _ The viewstart.cshtml file, which takes precedence over execution of any view in the same directory, can be used to specify a default layout.

@{    Layout = "~/views/shared/_layout.cshtml";}

This layout is the default layout for all views, and you can override the Layout property in the view if you have views that you do not want to have. If you do not want the layout, set layout= "".

third, partial view

The partial view is, by definition, part of a view that allows programmers to separate parts of the view from the pages they need to reference. Can reduce code duplication and improve page code reusability.

For example: The following is an action that returns a partial view

        Public ActionResult GetName ()        {            return partialview ();        }  

In any other view, just write the following code:

@Html. Partial ("GetName")
Or can be written like this
@{
Html.renderpartial ("GetName");
}

will be able to load the full code of the GetName view in the page. In general, the partial view should not include JS, or CSS because of this, is equal to the large view of the partial view of the JS and CSS, a good practice is the private JS and CSS through a section to introduce, so better. It is best not to have

@Html. Partial ("Partial View name")//have or the following three lines @{html.renderpartial ("Partial view name"); }

In addition, the partial view should pay attention to the overloads in @html.partial (), which are often useful, and if they are not, write their own extension methods. Take a look at the method signatures of these overloaded methods.

        public static mvchtmlstring Partial (This htmlhelper htmlhelper, string partialviewname);        public static mvchtmlstring Partial (This htmlhelper htmlhelper, string partialviewname, object model);        public static mvchtmlstring Partial (This htmlhelper htmlhelper, string partialviewname, Viewdatadictionary viewData); C4/>public static mvchtmlstring Partial (This htmlhelper htmlhelper, string Partialviewname, object model, Viewdatadictionary viewData);

As you can see from the method signature, these are extension methods, @Html. Partial is the data entity and data dictionary that can be given to a partial view, and then the partial view can be regenerated into a view over the data passed through the main views.

Give an example: pass a model past the partial view, and then the partial view side will interpret the view based on the incoming data. Look at the controller code.

Namespacemvcstart.controllers{PublicClassHomecontroller:controller {PublicActionResult Index () {Man_model man =NewMan_model (); Man. Id =1; Man. Name ="Zhang Fei"; Man. Age =23;ReturnView (man); }Public ActionResult GetName (ObjectO) {Man_model man = OAsMan_model;ReturnPartialview (man); } }Publicclass Man_model { Public int Id {get; setpublic string Name { Span style= "color: #0000ff;" >getsetpublic int Age {getset       

View Code: index.cshtml

@model mvcstart.controllers.man_model@model.id@model.age@html.partial ("GetId", model);

Getname.cshtml

@model MvcStart.Controllers.Man_Model<style= "" >> @Model. Name</div> 

The generated HTML code is:

<Html><Head><Title>index</title></head><< Span style= "color: #800000;" >body> 1 23<< Span style= "color: #800000;" >div style= "" >> Zhang Fei </div></body></< Span style= "color: #800000;" >html>           

The example is a bit far-fetched and does not see any effect, but really is to pass a man_model to the partial view through the main view, and then parse the returned HTML code by the partial views, what can this thing achieve? To give a simple example, if the code in the partial view is operated by the SEO staff, such as the page title, keywords, description, this value provides a box in the background to let the SEO staff settings, and the result is saved to the partial view of the code inside the words? So just pass in a model to the partial view, and the label of the partial view, such as Model.name, can automatically parse the real "Zhang Fei" data.

In 2013-5-5, there might have been some errors in understanding that the model can be passed to the partial view, but if a view loads a partial view, the partial view will have the same data as the data in the original page.

Let me give you an example of how

Controller code:

Namespacemvcapplication1.controllers{PublicClassHomecontroller:controller {PublicActionResult Index () {Person p =NewPerson (); P.id =1; P.name ="Tom"; viewdata["Abc"] ="Test ViewData";Return View (p);} public ActionResult indexpartial () {return View ();}} public class person { Span style= "color: #0000ff;" >public int Id {get< Span style= "color: #000000;" >;     setpublic string Name { Span style= "color: #0000ff;" >getset       

Main View Code:

@model MvcApplication1.Controllers.Person@{    viewbag.title = "Index";    Layout = "~/views/shared/_layout.cshtml";} @Model. Id@Model. Name@ViewData ["abc"] = "123"@Html. Partial ("indexpartial");    

Partial View Code:

@model MvcApplication1.Controllers.Person@{    viewbag.title = "indexpartial";    Layout = "~/views/shared/_layout.cshtml";} <br/> contents of the partial view @Model. Name@Model. Id@ViewData ["abc"] partial view content <BR />          

Notice that the main view does not pass any data to the partial views, but the execution results are as follows, and you can see that the partial view can actually get the data from the main views:

  

Again to record a trick, such as a Web site in debugging with a test path, after uploading with a real domain name, this time we can write the domain name in the configuration file or XML file, run is read, when we can define a static property, this property returns the real domain name. You can have a @ namespace in all views. class. Static variables get a real domain name. In other words, some small, changeable fragments in the view can be obtained in this way.

In addition, it is important to note that methods such as html.renderaction () also support incoming parameters in the following ways:

@Html. Renderaction ("left_nav"Nav3});    

How to call across regions:

@{html.renderaction ("Datagrid"DataList"Common"});     

Parameter values can be obtained by adding a parameter actionresult (int parentid) directly inside the action. Area is intercepted by MVC and analyzed for cross-region invocation.

  Difference:

  Partial partial view

There are also html.renderpartial and html.renderaction, which are used to display a relatively separate block of functionality in a template page.

The same point of partial and renderpartial

    Both are used to get a partial view.

The difference between partial and renderpartial

1. Partial has a return value (mvchtmlstring); renderpartial has no return value (Void).

A return value can be @html.partial ()

Without a return value directly @{html.partial ();}

Partial returns a string, so you can use a variable to receive the returned HTML string. But RenderPartial is writing the results into response, so there is no way to receive them with variables.

These two types of notation are equivalent.

The difference between action and renderaction

is used to introduce the code for an action, the difference is the same as the difference between partial and renderpartial above

The same point of the two

RenderPartial and renderaction are often used to display a relatively independent "block", such as a menu or a navigation bar. The results of both outputs are displayed as part of the view that is called.

Different points of the two
    1. Renderpatial's data comes from the calling view, and Renderaction comes from itself.
    2. Renderaction will initiate a new request, and renderpatial will not.
    3. The RenderPartial method is return Partialview (), and Renderaction is Return View ().

Common code for the ASP. NET MVC View

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.