0

I declare a class Name.cs to store some data:

namespace myproj.Data
{
    public class Name
    {
        public string[] items = new string[] {"item1", 
        "item2", "item3"}
    }
}

How can I use it in the _Layout.cshtml so that I can do something like:

@foreach (var item in Name.items)
{
    <div id="@item"></div>
}
4
  • Just as an addition to those answers marked above, I wouldn't strongly type a _Layout. If you need something passed to it to manipulate the output I would either pass it from the controller using ViewBag or I would have a ViewComponent to do the work and output to the view as needed. Commented Jan 8, 2020 at 8:52
  • @scgough Thank you for your help. After I saw some pages about partial views, I decided to pass a model to partial view. However, I am not sure if it is the best approach. I typed something like this in _Layout.cshtml : @model myproj.Models.SidebarData <partial name="_Sidebar.cshtml" model="Model"/> Commented Jan 9, 2020 at 3:52
  • @scgough I said that because it is a sidebar with data and contained in almost every view. I have to change return View() to return View("Index", new myproj.Models.SidebarData()) in every controller. Commented Jan 9, 2020 at 3:57
  • If change it to a ViewComponent. Lots of articles out there about them. That’s the newer way of doing this kind of thing. You can invoke it from the layout and it’s model can be obtained within the ViewComponent code (rather than passing the model on every action in every controller). Commented Jan 9, 2020 at 5:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.