剃刀代码以编程方式隐藏全局菜单项? [英] Razor code to programmatically hide global menu items?

查看:67
本文介绍了剃刀代码以编程方式隐藏全局菜单项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一位经验丰富的.NET程序员,但是对于整个Web编程我还是陌生的.我的ASP.NET MVC网站的全局布局包含一些内容(页面顶部的菜单链接),这些内容我想在控制器代码动态检测到的条件下隐藏.

I'm an experienced .NET programmer, but I'm new to this whole web programming thing. My ASP.NET MVC website has a global layout that includes some content (menu links at the top of the page) that I want to hide under conditions that are detected dynamically by controller code.

我的倾向-使用到目前为止所学到的工具的简单方法-是将一个布尔HideGlobal值推入ViewBag中,并将全局标记放入要隐藏在其中的_Layout.cshtml中@if(ViewBag.HideGlobal){}块的内容.

My inclination -- the simple approach that uses the tools I've learned about thus far -- is to shove a Boolean HideGlobal value into the ViewBag, and to put the global markup in _Layout.cshtml that I want to hide inside of an @if (ViewBag.HideGlobal){} block.

我只是想知道这是否是正确"的方式,还是出于我尚不明了的原因而应该使用一些剃刀魔法?

I just want to know if this is the "proper" way to do it, or is there some Razor magic that I should be using for reasons that are not yet evident to me?

推荐答案

我不喜欢在动作返回的视图之外使用动作的视图模型.在这种情况下使用基本视图模型会很麻烦.

I dislike using the view model of the action outside of the view returned by the action. Using base view model for this scenario feels very clunky.

我相信,使用单独的(子)动作更干净,更明显,该动作包含用于指定应如何显示全局菜单的逻辑.此操作将返回全局菜单视图.从布局页面调用该操作.

I believe it's cleaner and more obvious to just use a separate (child) action that contains the logic for specifying how the global menu should be displayed. This action returns the global menu view. Call that action from your layout page.

或者您可以为确定菜单状态的整个标题创建一个动作-或执行if/else呈现全局菜单的部分视图.

Or you can create an action for the entire header where the menu's state is determined -- or do an if/else to render a partial view of the global menu.

下面的示例封装了标题/全局菜单的需求,并提供了一种在不影响代码基础结构(基本视图模型)的情况下更改标题/菜单的未来方法.

The example below encapsulates the needs of a header/global menu and offers a future proof way of changing your header/menu with minimal effect on your code infrastructure (base view model).

〜/Controllers/LayoutController.cs

public class LayoutController : Controller
{
    [ChildActionOnly]
    public ActionResult Header()
    {
        var model = new HeaderViewModel();
        model.ShowGlobalMenu = ShowGobalMenu();

        return View(model);
    }
}

〜/Views/Layout/Header.cshtml

@model HeaderViewModel
@{
    Layout = "";
}

<header>
    <a href="/">Home</a>

    @if(Model.ShowGlobalMenu)
    {
        <ul>
            <li><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
            <li><a href="#">Link</a></li>
        </ul>
    }
</header>

〜/Views/Shared/_Layout.cshtml

<html>
    <body>
        @Html.Action("Header", "Layout")

        <p>Stuff</p>
    </body>
</body>

这篇关于剃刀代码以编程方式隐藏全局菜单项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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