Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor code to programmatically hide global menu items?

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.

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?

like image 460
Bob.at.Indigo.Health Avatar asked May 19 '26 19:05

Bob.at.Indigo.Health


1 Answers

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.

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>
like image 146
Omar Avatar answered May 22 '26 16:05

Omar