Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give shared layout a model in Razor MVC?

I'm trying to give a model to the shared layout so the menu links are created dynamically from a database. Any ideas where I should start?

I am looking for maybe tutorials of how to use inheritance to do this?

like image 542
Beginner Avatar asked Dec 13 '11 10:12

Beginner


People also ask

How to create shared razor layout&viewstart in MVC 5?

In this blog you will learn about ASP.NET MVC 5 Create Shared Razor Layout & ViewStart. In article, I have shared a way to create a Layout Razor and ViewStart in ASP.NET MVC 5. You need to create a shared folder, "Shared" in the Views directory. Go Views/Shared directory and create new _LayoutPage1.cshtml file and write the following below code.

What is the difference between Razor pages and controllers with views?

This document discusses layouts for the two different approaches to ASP.NET Core MVC: Razor Pages and controllers with views. For this topic, the differences are minimal: Razor Pages are in the Pages folder. Controllers with views uses a Views folder for views.

What is layout view in ASP NET MVC?

ASP.NET MVC introduced a Layout view which contains these common UI portions so that we don't have to write the same code in every page. The layout view is the same as the master page of the ASP.NET webform application.

How do I specify a layout in Razor View engine?

Specifying a Layout. The layout specified can use a full path (for example, /Pages/Shared/_Layout.cshtml or /Views/Shared/_Layout.cshtml) or a partial name (example: _Layout ). When a partial name is provided, the Razor view engine will search for the layout file using its standard discovery process.


1 Answers

You could do this:

Model

public partial class Menu
{
    public String[] items;

    public Menu(String[] items)
    {
        this.items = items;
    }
}

View (_Menu)

@model YourMVC.Models.Menu

<ul>
    @foreach (String item in Model.items)
    {
        <li>@item</li>
    }
</ul>

Place this in _Layout

@Html.Action("_Menu", "Home")

Controller (HomeController)

public ActionResult _Menu()
{
    String[] items = {"Item1", "Item2", "Item3", "Item4"};

    return PartialView(new Menu(items));
}

Of course in your actual implementation you would grab whatever you needed from the database in the controller _Menu() action.

I'm not sure if this implementation is the best practice, but it certainly works.

like image 123
Drew Gaynor Avatar answered Oct 22 '22 08:10

Drew Gaynor