NullReference
NullReference

Reputation: 4484

How to get MVC to ignore undefined sections?

In ASP.NET MVC 3 if you define a section in a view that isn't defined in the layout you get an exception thrown. Is there a way mark the section option from the view ?

Upvotes: 1

Views: 1270

Answers (3)

VJAI
VJAI

Reputation: 32768

You can't render a section in a view that is not defined in the layout.

You can assume like layout is an abstract class and view is a concrete implementation. The section defined in layouts are nothing but abstract methods that will be implemented in views.

So adding a section in view that is not defined in layout is kind of implementing an abstract method that even not exists. And if you define a section in a view it is like adding an abstract method to a concrete class and that changes the view into a layout. Hope this answers your question.

Upvotes: 1

naspinski
naspinski

Reputation: 34707

@RenderSection("SomeSection", false)
@if (!IsSectionDefined("SomeSection")) { }

The second part is not necessary, but if you want to do sometheing by default if it is not available.

Upvotes: 0

Sergey Rybalkin
Sergey Rybalkin

Reputation: 3026

Sure, there is an overload for RenderSection method that takes second parameter which defines whether the section is required:

@RenderSection("javascript", false)

Upvotes: 1

Related Questions