Reputation: 4870
I was wondering if someone here could shed some light on some questions I was having lately about Razor.
1) Basically, I wanted to split section definition into multiple parts? Why? Because I wanted to.
Sadly using @section "sectionname" twice threw an exception.
Looking deeper into the Razor source, I saw that Razor checked if a section had already been defined and threw an exception if it was already defined.
As Razor uses delegates to render sections, I changed the code to use Delegate.Combine (if a section had been defined before), and it worked, I was now able to create a Section that was declared twice (or more).
2) When a section is defined in a View but not rendered in the layout page an Exception is thrown. I haven't seen an elegant solution to overcome this. If I want to use a View page with multiple layout pages... This is kind of a problem.
Looking at the source (again) there's just a foreach that checks if every section defined in the view has been rendered, and then it throws an exception if a section hasn't been rendered.
I have thought of some solutions (especially for my second question, inheriting from the view base class and exposing the non-rendered sections to the layout page and doing some handling), but they seem... kind of like hacks. Are there any better solutions then actually changing the source?
Not really important, but if anyone also has any insight on the design decisions that led Razor to be this way, I'd also be grateful, as this seems to be a very restrictive design.
update:
@davidferguson and @takepara you've got it wrong. My problem isn't with defining a section in the layout, and not defining it in the view, but the other way around. Defining it in the View but not defining it in the layout.
Upvotes: 3
Views: 1746
Reputation: 4791
1) Unfortunately that was a design decision made early on in the product as there is huge issues around merging sections together and in what order. Not saying that we couldn't do it but with the time frame we had it just wasn't possible to support it as a first class citizen in all scenarios.
2) This is an interesting idea. There really isn't an good solution to this other than changing the source code. However, I have opened an issue for a feature for vNext that would allow for this type of scenario. (No promises that it will make the cut though)
Upvotes: 5
Reputation: 760
To stop an exception being thrown when a section is not used on a view use the required parameter.
@RenderSection("sectionname", required: false)
using this if any view does not implement this section no exception will be thrown.
Upvotes: 5
Reputation: 10433
Defining Default Content For A Razor Layout Section
This is very nice entry.
Upvotes: 1