Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I optionally render a section in ASP.Net MVC 3?

On my website, I have a section (a floating sidebar) that I want rendered only for a sub-set of users (admins). I'm hoping that I can put the logic in the master layout for determining if the section should be shown or not but that causes an error on the page if the section isn't rendered.

Example code - Layout.cshtml...

... code ...
@if(user.IsAdmin) {
    @RenderSection("AdminSidebar", false)
}

Example code - MyPage.cshtml...

@section AdminSidebar {
    ... code ...
}

Does anybody know how to get this to work without having to put the logic in all of the child pages?

As a note, IsSectionDefined("AdminSidebar") only works in the layout file. It doesn't work in the page to test if the section is available or not.

like image 561
Brian Avatar asked Nov 07 '11 17:11

Brian


1 Answers

I don't know if this is not abusing the framework, but if you're really inclined to go that way you could try the following:

@{
    if(user.IsAdmin) {
        @RenderSection("AdminSidebar", false)
    } 
    else {
        RenderSection("AdminSidebar", false).WriteTo(TextWriter.Null);
    }
}
like image 193
João Angelo Avatar answered Oct 11 '22 14:10

João Angelo