Html.partial and HTML. renderpartial

Source: Internet
Author: User
Tags httpcontext actionlink

Templars-Blue Sword Action

Html.partial and HTML. RenderPartial usage
    1. Html.partial and HTML. RenderPartial usage

The usage and difference of html.partial and renderpartial
Html.partial and renderpartial are output HTML fragments, the difference is
Partial is to directly generate a string of the view content and return (equivalent to an escape process), the RenderPartial method is output directly to the current HttpContext (because it is a direct output, so good performance). So they are used differently in the view:
MVC2:
Output to HttpContext
Output as string directly to page
MVC3:
@Html. Partial ("Basicchart")
@{
Html.renderpartial ("Basicchart");
}
The other three overloads of Html.partial and renderpartial are useful, the second overload @{html.renderpartial ("Basicchart", model);}
With this overload, you can use a strong type in a partial view, then use the second parameter in the main master to pass the model past without the controller
such as a list of one of the MyClass past
The third overload is used to transmit ViewData, such as: @{html.renderpartial ("Basicchart", viewdata["MyData"]);}

Example:

<div id= "Logindisplay" >

@* @Html. Partial ("_logonpartial") *@

@{

Html.renderpartial ("_logonpartial");

}

</div>

Other: Related information:

@RenderBody , @RenderSection , @RenderPage , html.renderpartial , html.renderaction the role and the difference

1. Renderbody
There is no "master page" in the Razor engine, instead a page called "Layout" (_layout.cshtml) is placed in the shared view folder. In this page, you will see a statement in the label:
@RenderBody ()
In fact, it works like a server control in a master page, when you create a view based on this layout page, the contents of the view are merged with the layout page, and the contents of the newly created view are rendered between the labels through the @renderbody () method of the layout page.
This method does not require parameters and can only occur once.

2. Renderpage
From the name can guess this method is to render a page. For example, the fixed head of the Web page can be placed in a shared view file, and then in the layout page through this method call, use the following:
@RenderPage ("~/views/shared/_header.cshtml")
With parameters
@RenderPage ("~/views/shared/_header.cshtml", new{parm= "my", parm2= "You")
Invoke page Get Parameters:
Gets the arguments passed by the Renderpage ().
@PageData ["Param"]

3. Rendersection
The layout page also has the concept of section, which means that if a section is defined in a view template, it can be rendered separately, using the following:
@RenderPage ("~/views/shared/_header.cshtml")
@RenderBody ()
A section is added to the template.
@RenderSection ("Head")
Of course, you also define the section in the view, otherwise an exception will occur:
@section head{
Do
}
To prevent exceptions due to a missing section, you can provide a 2nd parameter to Rendersection ():
@RenderSection ("submenu", false)
Or
@if (issectiondefined ("submenu"))
{
@RenderSection ("submenu", false)
}
Else
{
<p>submenu section was not defined!</p>
}

[Email protected]
The Partial creates its own TextWriter instance each time and caches the content in memory. Finally, the contents of all writer outputs are sent to a Mvcstring object.
More often we will use @{html.renderpartial ("Details");} instead of @html.partial

The difference between renderpage () and renderpartial ()

A page called by Renderpage () can only use it to pass past data.
RenderPartial () can use data such as Viewdata,model.

The difference between html.renderpartial and html.renderaction

Html.renderpartial is suitable for use in repeated use of the UserControl, and only need to show the content through the model, or for advertising UserControl is also suitable. Html.renderaction will call the Controller's action method first, if this UserControl need to get data through the database to render (through action to read the database), it is more appropriate to use this method.

5.html.partial ("MyView")

Returns an attempt stream in the form of mvchtmlstring, followed by a standard routing rule.

Renders the "MyView" view to an mvchtmlstring. It follows the standard Rules for view lookup (i.e. check in current directory and then check the Shared directory).

Html.renderpartial ("MyView")

Similar to Html.partial (), the difference is that it is entered directly into the page without caching.

Does the same as html.partial (), except that it writes its output directly to the response stream. This was more efficient, because the view content was not buffered in memory. However, because the method does not return any output, @Html. RenderPartial ("MyView") won ' t work. You have to wrap the call in a code block instead: @{html.renderpartial ("MyView");}.

Renderpage ("myview.cshtml")

Returns a special view with a path, file name, and so on, directly out of the same heml.renderpartial (), without caching. Model variables can be passed.

Renders the specified view (identified by path and file name rather than by view name) directly to the response stream, Li Ke html.renderpartial (). You can supply any model you like to the view by including it as a second parameter

Renderpage ("myview.cshtml", MyModel)

I prefer

@RenderPage ("_layoutheader.cshtml")

Over

@{html.renderpartial ("_layoutheader");}

Only because the syntax is easier and it's more readable. Other than, there doesn ' t seem to is any differences functionality wise.

2.<span> @Html. Raw ("AAA<BR/>BB") </span>

Output to AAA

Bb

@{

Viewbag.title = "Index<br/>aa";

}

<span> @ViewBag .title</span>

Output is INDEX<BR/>AA

ASP. MVC3.0 @html.partial, @Html. Action, @Html. renderpartial, @Html. renderaction

1. The return value of the method with render is void, output inside the method, and the return value type is mvchtmlstring, so this can only be used:

@Html. Partial corresponds to @{html.renderpartial (...);}

@Html. Action corresponds to @{html.renderaction (...);}

2, html.partial can directly provide the user control name as a parameter,

The html.action needs to have a corresponding action, which returns Partailresult (that is, Retun Partialview ()) within the action.

3, for a simple user control without any logic, it is recommended to use html.partial; for user controls that need to set some model, Html.action is recommended. Of course, there are model data can also use the Html.partial method, you can see the overloads of the method.

4, the use of html.action has the advantage that can be based on different scenarios to choose a different user control. For example: @Html. Action ("Userinfocontrol") in the corresponding Userinfocontrol this action, when the user is not logged in, you can Retun Partialview ("Logonusercontrol" ); After logging in, you can Retun Partialview ("Userinfocontrol");

html.partial and the html.renderpartial, Html.action and the html.renderaction the Difference

Html.partial returns a string that html.renderpartial writes the content to response, returning void

In Razor, the following 2 notation is equivalent:

@Html. Partial ("ViewName")      @{html.renderpartial ("ViewName"); }

You can use Html.partial to save the output of the Partial view to a variable, but html.renderpartial not.

Html.renderpartial will write the output directly into the response at the time of execution.

The difference between html.action and Html.renderaction is the same as above.

3. MVC Ajax Helpers

There are many ways to implement Ajax in MVC, with Microsoft's own Microsoftajax, or with jquery Ajax, and if you are familiar with other JavaScript frameworks, you can use other implementations, such as prototype and so on.

The following are Microsoft's own implementation scenarios.

JavaScript files that require pre-loading:

<script src= "@Url. Content (" ~/scripts/microsoftajax.js ")" Type= "Text/javascript" ></script>
<script src= "@Url. Content (" ~/scripts/microsoftmvcajax.js ")" Type= "Text/javascript" ></script>

Some of the following ready-made HTML Hepler have been provided in MVC:

    • Ajax.actionlink ()
    • Ajax.beginform ()
    • Ajax.routelink ()
    • Ajax.beginrouteform ()

Ajax.actionlink

Methods for sending asynchronous requests using ActionLink:

View

<div id= "MYPNL" style= "width:300px; height:30px; border:1px dotted silver; " >
</div>
@Ajax. ActionLink ("Click Me", "GetTime", new ajaxoptions {Updatetargetid = "MYPNL"})

Controller

Public ActionResult GetTime ()
{
Return Content (DateTime.Now.ToString ());
}

The example above uses the ActionLink hyperlink to send a request to gettime, which returns a contentresult that specifies the page element that needs to be updated through the Updatetargetid property in Ajaxoptions.

There are other properties that you can specify in Ajaxoptions:

Confirm

Equivalent to return confirm (msg) in JavaScript, the information that needs confirmation is first prompted when you click on the link.

HttpMethod

Specifies that HTTP requests are sent using GET or post

Insertmode

There are three ways to specify which method to update data in the specified Updatetargetid element:

"InsertAfter", "InsertBefore", or "Replace". The default is: Replace

Loadingelementduration

Loading the time the element is displayed

Loadingelementid

You can specify the loading element that is displayed during an HTTP request

Onbegin

JavaScript methods that are executed before HTTP requests

OnComplete

Methods to execute at the end of an HTTP request

OnFailure

Methods to execute when an HTTP request fails

Onsuccess

Methods to execute when an HTTP request succeeds

Updatetargetid

HTTP requests for updated page elements

Url

URL of the HTTP request

The use of methods in Ajaxoptions, in the previous article on the introduction of ActionResult, has been related to the following:

Jsonresult

Watch out.

    • The difference between OnComplete and onsuccess: OnComplete is raised when an HTTP request is obtained, and the page has not been updated, and onsuccess is raised after the page has been updated.
    • The relationship between the URLs in ActionName and ajaxoption in ActionLink: The HTML of the two are as follows, but the result is the same, I hope there is a master can explain whether the difference between the two.

<a href= "/home/gettime" data-ajax-update= "#myPnl" data-ajax-mode= "Replace" data-ajax= "true" >click me</a >
<a href= "/" Data-ajax-url= "Home/gettime" data-ajax-update= "#myPnl" data-ajax-mode= "Replace" data-ajax= "true" > Click me</a>

Ajax.beginform

The HTML Hepler can be implemented using AJAX to submit the form, displaying the result of the submission in the specified page element.

View

@model MvcAjax.Models.UserModel
@{
Viewbag.title = "Ajaxform";
}
<div id= "MYPNL" style= "width:300px; height:30px; border:1px dotted silver; " >
</div>
@using (Ajax.beginform ("Saveuser", new ajaxoptions {Updatetargetid = "MYPNL"})
{
<table>
<tr>
<td>
@Html. labelfor (M = m.username)
</td>
<td>
@Html. textboxfor (M = m.username)
</td>
</tr>
<tr>
<td>
@Html. labelfor (M = m.email)
</td>
<td>
@Html. textboxfor (M = m.email)
</td>
</tr>
<tr>
<td>
@Html. labelfor (M = m.desc)
</td>
<td>
@Html. textboxfor (M = m.desc)
</td>
</tr>
<tr>
<TD colspan= "2" >
<input type= "Submit" value= "Submit"/>
</td>
</tr>
</table>

Model

Using System.ComponentModel.DataAnnotations;
Namespace Mvcajax.models
{
public class Usermodel
{
[Display (Name = "Username")]
public string UserName {get; set;}
[Display (Name = "Email")]
public string Email {get; set;}
[Display (Name = "Description")]
public string Desc {get; set;}
}
}

Controller

Public ActionResult Ajaxform ()
{
return View ();
}
[HttpPost]
Public ActionResult Saveuser (Usermodel Usermodel)
{
Save User Code here
//......
Return Content ("Save complete!");
}

The example code above implements the approximate method of submitting form data using AJAX, using Ajaxoptions in Ajax.beginform to set the parameters of the AJAX request in the same way as in Ajax.actionlink.

Other:

When introducing Javascriptresult, it was mentioned that the ActionResult was directly reponse as a file in a normal request, but in an AJAX request, the result can be used and the JavaScript in result will be executed.

For example, change the above Conntroller to the following code:

[HttpPost]
Public ActionResult Saveuser (Usermodel Usermodel)
{
Save User Code here
//......
Return Content ("Save complete!");
Return JavaScript ("alert (' Save complete! ');");

The statements in Javascriptresult can be executed after the AJAX request is executed.

Html.partial and HTML. renderpartial

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.