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>
}
Harry
  • 31
  • 1
  • 8
  • 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. – scgough Jan 08 '20 at 08: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` `` – Harry Jan 09 '20 at 03: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. – Harry Jan 09 '20 at 03: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). – scgough Jan 09 '20 at 05:46

0 Answers0