我如何选择性呈现在ASP.Net MVC 3节? [英] How do I optionally render a section in ASP.Net MVC 3?

查看:163
本文介绍了我如何选择性呈现在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.

举例code - Layout.cshtml ...

Example code - Layout.cshtml...

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

举例code - MyPage.cshtml ...

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?

作为一个说明,IsSectionDefined(AdminSidebar)只能在布局文件。它不会在页面工作以测试是否部分是可用的或不

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.

推荐答案

我不知道这是不是滥用的框架,但是如果你真的倾向于采用这种方式,你可以尝试以下方法:

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

这篇关于我如何选择性呈现在ASP.Net MVC 3节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆