开发者

Razor view engine RenderSection

开发者 https://www.devze.com 2023-01-25 16:54 出处:网络
I am really digging this new Razor View Engine... For someone just coming from another web platform the new MVC 3 efforts are starting to feel right at home for me...

I am really digging this new Razor View Engine... For someone just coming from another web platform the new MVC 3 efforts are starting to feel right at home for me...

My question is about sections, I see it is possible to define sections in your layout and inject content into them but from all the samples I have seen it appears that this is done from the view. For me it makes more sense to assign content or output for each section from the controller.

So if I have a layout that contains a side bar that I want to load 开发者_运维技巧widgets into my view file should not be responsible for rendering the content into those sections. If this were the case then if the side bar content was shared across multiple views then I would have to duplicate that code across view files. My view files should be ignorant of what content is rendered in the side bar next to them.

Ideally I would like to assign content to my sections in the side bar from my controller so my question, is this possible?


In ASP.NET MVC (and other MVC based web application architectures) controllers prepare the data that is rendered by the views. How, where and maybe even when this data is rendered is the view's job to figure out. This is of course more of a architectural design discussion.

A nice thing about ASP.NET MVC is their 'convention over configuration' standpoint which (especially with Razor) lets you change how a lot of things behave. I don't think there's a View.Sections["section1"] = <some data>; option, but you could make a ViewModel that is based on sections, then have some generic master view that just takes apart this ViewModel and sends the correct data to correct partial views. This view model for sections could even hold HTML that has to be rendered, as Razor can be used made to render HTML outside .cshtml files. For more go to Andrew Nures' blog: http://blog.andrewnurse.net/

As you can see this transfers a lot of responsibility from view to the controllers. I myself like that rendering is totally separated from the controllers as then I can hypothetically build very different websites just by changing how data is rendered.

0

精彩评论

暂无评论...
验证码 换一张
取 消