ASP.NET MVC 3 Razor Templates VS RenderPartial

假装没事ソ 提交于 2019-12-02 15:53:41

Well, you should ask the author of that post about his motivation for presenting this technique.

It certainly illustrates what is possible in Razor. Whether you should use it is a different matter. I personally think that there are alternative techniques that are less complicated (I agree with your points about storing a Func inside of the request context).

  • There's @RenderPartial which you already mentioned.
  • You can also use the @helper syntax (either as a local helper or a global helper)
  • You can write an html helper (and use TagBuilder to assemble the output)
  • You can write a child action
  • You can write a templated helper

Now that I look at the above list I think MVC might provide too much choice :)

Update To better illustrate how inline templates can be useful I wrote a blog post about using them to call sections with default code: Optional Razor Sections with Default Content.

You can use it to write something like this:

@this.RenderSection("OptionalSection", @<div>Default Content</div>) 
Mrchief

A common misconception about Razor is that it can't be used outside the context of the ASP.Net MVC framework. It is the most common scenario, however the power of razor engine goes beyond that.

You can define razor templates in a console app or even a library. As a over simplified example, consider an app that sends automated HTML emails to clients. In old days, you would either resort to string concatenation or XSLT transform or something else. Either way, you cannot visually see your markup and manipulation becomes a maintenance nightmare.

With Razor templates, you can define your template as HTML markup where you can easily visualize and test it.

Here's an excellent article that demonstrates this capability: http://www.west-wind.com/weblog/posts/2010/Dec/27/Hosting-the-Razor-Engine-for-Templating-in-NonWeb-Applications

Note: I'm not saying that the link you pointed is showing this, just an example of why you would want to go beyond the methods listed in @marcind's answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!