How do I optionally render a section in ASP.Net MV

2019-04-04 18:06发布

问题:

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.

回答1:

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);
    }
}


回答2:

In my _Layout.cshtml file I did something like this:

@if(user.IsAdmin)
{
   @Html.Partial("SideBar")
}

to avoid having to have all of the child pages have to deal with the optional section in essentially the same manner. When I first tried the optional section thing, I found that I was repeating myself in the child pages, at least in my implementation.

Where I've used the @RenderSection call for optional sections, it has generally been to provide page-specific stuff.



回答3:

Using a section for something that is conditional based on the users permission level feels a little dirty to me. I would use RenderPartial(user) and put the logic in the partial.

    @if(user.IsAdmin) {
       ..code..
     }