Html.Partial和Html. RenderPartial用法

  1. Html.Partial和Html. RenderPartial用法

Html.partial和RenderPartial的用法与区别

Html.partial和RenderPartial都是输出html片段,区别在于

Partial是将视图内容直接生成一个字符串并返回(相当于有个转义的过程),RenderPartial方法是直接输出至当前 HttpContext(因为是直接输出,所以性能好)。因此它们在视图中的使用方式是不同的:

MVC2:

输出到 HttpContext

输出为string 直接到页面

MVC3:

@Html.Partial("BasicChart")

@{

Html.RenderPartial("BasicChart");

}

Html.partial和RenderPartial的其它三个重载很有用,第二个重载@{Html.RenderPartial("BasicChart",model);}

用这个重载可以在部分视图里使用强类型,然后在主视图中使用第二个参数传model过去,而不用controller

比如从list中传其中一项myClass过去

第三个重载用来传ViewData同理,如:@{Html.RenderPartial("BasicChart",ViewData["myData"]);}

示例:

<div >

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

@{

Html.RenderPartial("_LogOnPartial");

}

</div>

另:相关资料:

@RenderBody@RenderSection@RenderPageHtml.RenderPartialHtml.RenderAction的作用和区别

1. RenderBody

在Razor引擎中没有了“母版页”,取而代之的是叫做“布局”的页面(_Layout.cshtml)放在了共享视图文件夹中。在这个页面中,会看到标签里有这样一条语句:

@RenderBody()

其实它的作用和母版页中的服务器控件类似,当创建基于此布局页面的视图时,视图的内容会和布局页面合并,而新创建视图的内容会通过布局页面的@RenderBody()方法呈现在标签之间。

这个方法不需要参数,而且只能出现一次。

2. RenderPage

从名称可以猜出来这个方法是要呈现一个页面。比如网页中固定的头部可以单独放在一个共享的视图文件中,然后在布局页面中通过这个方法调用,用法如下:

@RenderPage(“~/Views/Shared/_Header.cshtml”)

带参数

@RenderPage(“~/Views/Shared/_Header.cshtml”,new{parm="my",parm2="you")

调用页面获取参数:

//获取 RenderPage() 传递过来的参数

@PageData["param"]

3. RenderSection

布局页面还有节(Section)的概念,也就是说,如果某个视图模板中定义了一个节,那么可以把它单独呈现出来,用法如下:

@RenderPage(“~/Views/Shared/_Header.cshtml”)

@RenderBody()

//模板里添加了一个节

@RenderSection(“head”)

当然还要在视图中定义节,否则会出现异常:

@section head{

//do

}

为了防止因缺少节而出现异常,可以给RenderSection()提供第2个参数:

@RenderSection("SubMenu", false)

@if (IsSectionDefined("SubMenu"))

{

@RenderSection("SubMenu", false)

}

else

{

<p>SubMenu Section is not defined!</p>

}

4.@Html.Partial

 Partial 每次都会创建自己的 TextWriter 实例并且把内容缓存在内存中. 最后把所有 writer输出的内容发送到一个 MvcString对象中

更多时候我们会使用 @{ Html.RenderPartial("Details"); } 而不是@Html.Partial

RenderPage()和RenderPartial()的区别

RenderPage()调用的页面只能使用其传递过去的数据。

而RenderPartial()是可以使用viewdata,model等数据的。

Html.RenderPartial和Html.RenderAction的区别

Html.RenderPartial适合用在重覆使用的UserControl,并且只需要透过Model来呈现内容,或是对于广告的UserControl也适合使用。 Html.RenderAction则会先去呼叫Controller的Action方法,如果此UserControl是需要透过资料库取得资料来呈现(透过Action来读取资料库),此时会比较适合使用此方式。

5.Html.Partial("MyView")

以MvcHtmlString形式返回试图流,遵循标准的路由规则。

Renders the "MyView" view to an MvcHtmlString. It follows the standard rules for view lookup (i.e. check current directory, then check the Shared directory).

Html.RenderPartial("MyView")

与Html.Partial()类似,区别是直接输入到页面,不进行缓存。

Does the same as Html.Partial(), except that it writes its output directly to the response stream. This is more efficient, because the view content is 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")

返回带路径、文件名等的特殊视图,同Heml.RenderPartial()一样直接输出,不进行缓存。可以传递model变量。

Renders the specified view (identified by path and file name rather than by view name) directly to the response stream, like 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 is more readable. Other than that there doesn't seem to be any differences functionality wise.

2.<span>@Html.Raw("aaa<br/>bb")</span>

输出为aaa

bb

@{

ViewBag.Title = "Index<br/>aa";

}

<span>@ViewBag.Title</span>

输出为Index<br/>aa

asp.net MVC3.0 中@Html.Partial,@Html.Action,@Html.RenderPartial,@Html.RenderAction

1、带有Render的方法返回值是void,在方法内部进行输出;不带的返回值类型为MvcHtmlString,所以只能这样使用:

@Html.Partial 对应 @{Html.RenderPartial(....);}

@Html.Action 对应 @{Html.RenderAction(....);}

2、Html.Partial可以直接提供用户控件名作为参数,

而Html.Action需要有对应的Action,在Action内部返回PartailResult(即retun PartialView())。

3、对于简单的没有任何逻辑的用户控件,推荐使用Html.Partial;对于需要设置一些Model的用户控件,推荐使用Html.Action。当然,有Model数据也是可以使用Html.Partial方法的,可以看方法的重载。

4、使用Html.Action有个好处,就是可以根据不同的场景选择不同的用户控件。比如:@Html.Action("UserInfoControl")在对应的 UserInfoControl这个Action中,在用户未登录的时候,可以retun PartialView("LogOnUserControl");登录后,可以retun PartialView("UserInfoControl");

Html.PartialHtml.RenderPartial, Html.ActionHtml.RenderAction的区别

Html.Partial返回的是一个字符串, Html.RenderPartial会将内容写入到response中, 返回void

在Razor中,下面2中写法是等价的:

@Html.Partial("ViewName") 
   
  @{Html.RenderPartial("ViewName");  }

你可以使用 Html.Partial, 把Partial View的输出保存到变量中, 但是Html.RenderPartial不行.

Html.RenderPartial会在执行的时候,直接把输出写进Response.

Html.Action和Html.RenderAction的区别和上面的就是一样的了。

在MVC中要实现Ajax有很多的方式,有微软自己的MicrosoftAjax,也可以用JQuery的AJax来实现,如果对其他的JavaScript框架熟悉,还可以采用其他的实现方案,比如说Prototype等等。

以下是微软自己的实现方案。

需要预先加载的JavaScript文件:

    <script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>

在MVC中已经提供了下面几个现成的HTML Hepler:

  • Ajax.ActionLink()
  • Ajax.BeginForm()
  • Ajax.RouteLink()
  • Ajax.BeginRouteForm()

Ajax.ActionLink

使用ActionLink发送异步请求的方法:

View

<div >
</div>
@Ajax.ActionLink("Click Me", "GetTime", new AjaxOptions { UpdateTargetId = "myPnl" })

Controller

public ActionResult GetTime()
{
    return Content(DateTime.Now.ToString());
}

以上示例使用ActionLink超链接发送请求到GetTime,返回一个ContentResult,通过AjaxOptions中的UpdateTargetId属性指定了需要更新的页面元素。

AjaxOptions中还有其他可以指定的属性:

Confirm

等效于javascript中的return confirm(msg),在点击该链接时先提示需要确认的信息。

HttpMethod

指定使用Get或者是Post方式发送Http请求

InsertMode

指定使用哪一种方式在指定的UpdateTargetId元素更新数据,可以有三种方式:

"InsertAfter", "InsertBefore", or "Replace" 。默认为:Replace

LoadingElementDuration

Loading元素显示的时间

LoadingElementId

可以指定在Http请求期间显示的Loading元素

OnBegin

在Http请求之前执行的javascript方法

OnComplete

在Http请求结束时执行的方法

OnFailure

在Http请求失败时执行的方法

OnSuccess

在Http请求成功时执行的方法

UpdateTargetId

Http请求更新的页面元素

Url

Http请求的Url

关于AjaxOptions中各方法的使用方法,在之前关于ActionResult的介绍的文章中有相关的列子:

JsonResult

注意点

  • OnComplete和OnSuccess的区别:OnComplete是获取了Http请求时引发的,此时页面还没有进行更新,OnSuccess是在页面已经更新后引发的。
  • ActionLink中的actionName和AjaxOption中的Url的关系:两者分别产生的HTML如下,但是执行的结果相同,希望有高手能解释下这两者有无区别。

<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

该Html Hepler可以实现使用Ajax方式提交Form,在指定的页面元素中显示提交的结果。

View

@model MvcAjax.Models.UserModel
@{
    ViewBag.Title = "AjaxForm";
}
<div >
</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!");
}

以上示例代码实现了采用Ajax提交Form数据的大概方法,在Ajax.BeginForm中同样使用AjaxOptions来设置Ajax请求的参数,和Ajax.ActionLink中的使用方法相同。

其他:

介绍JavaScriptResult时曾经提到了该ActionResult在普通的请求中是直接当作文件Reponse出的,但是在Ajax请求中,便可以使用该Result,并且执行Result中的JavaScript。

比如将上面的Conntroller更改为以下代码:

[HttpPost]
public ActionResult SaveUser(UserModel userModel)
{
    //Save User Code Here
    //......
    //return Content("Save Complete!");
    return JavaScript("alert('Save Complete!');");
}   

便可在执行改Ajax请求之后执行JavaScriptResult中的语句。