MVCRazor中有不同的展现partialview的方法,许多开发人员子在选择使用RenderPartial or RenderAction or Partial or Action helper 方法时比较困惑,不知该选择哪一个,这篇文章,我向大家介绍一下Html.RenderPartial, Html.RenderAction, Html.Partial & Html.Action的不同
Html.RenderPartial
1. 这个方法会直接将结果写入到当前请求的httpresponse数据流中,这意味着它使用了和当前webpage/template使用的相同的TextWriter对象
2. 方法没有返回值
3. 不需要创建action,使用简单
4. 如果和partialview对应的viewmodel中,已经存在了partialview展示所需数据,RenderPartial方法会很有用.For example :blog中,显示一篇文章和它的评论,RenderPartial方法会是比较好的选择,既然文章的评论信息已经存在在viewmodel中
@{Html.RenderPartial("_Comments");}
5. 这个方法比partial方法更快,因为它直接将结果系统到当前响应的数据流中
Html.RenderAction
1. 和上一个一样,执行结果会直接写入当前响应的数据流中
2. 需要创建childaction方法.
3. 如果partialview的数据独立于对应的view的viewmodel,则这个方法比较有用,Forexample : Iblog中每个页面都显示不同的类目菜单,我们最好选择使用RenderAction既然类目数据是由不同的model提供
@{Html.RenderAction("Category","Home");}
4. 如果你想缓存partialview,这是最好的选择。
5. 这个方法比action方法快,基于第一条原因
Html.Partial
1. 结果以HTML-encoded字符串展示
2. 返回的是string类型,所以结果可以存储在变量里.
3. 使用简单,无需创建action
4. Partial method is useful usedwhen the displaying data in the partial view is already in the correspondingview model.For example: In a blog to show comments of an article, we would liketo use RenderPartial method since an article information with comments arealready populated in the view model.
@Html.Partial("_Comments")
Html.Action
1. 结果直接展示为HtmlString.
2. 需要创建对应的child action
3. 返回字符串,可以存储在变量里.
4. Action method is useful whenthe displaying data in the partial view is independent from corresponding viewmodel.For example: In a blog to show category list on each and every page,we would like to use Action method since the list of category is populated bythe different model.
@{Html.Action("Category","Home");}
5. 可以缓存partialview.
转自:
http://blog.csdn.net/kufeiyun/article/details/9377065