Search code examples
c#asp.net-mvc-5

problem to access a model property from _layout.cshtml


Check the code bellow. I am using c# mvc5 and trying to loop over a model from _Layout.cshtml but when i try to access AllModuleTypes property from Model MainLayoutData visual studio intellisense shows error: member cannot be accessed with an instance reference qualify it with a type name instead. Whats wrong i am doing?

Model:

public class MainLayoutData
{
    public static List<ModuleTypes> AllModuleTypes { get; set; } 
}

Controller:

public ActionResult Index()
{
    using (var ctx = new TestEntities())
    {
        var modTypes = ctx.ModuleTypes.ToList();
        var mainlayData = new MainLayoutData();
        MainLayoutData.AllModuleTypes = modTypes;

        return View(mainlayData);
    }
}

_Layout.cshtml:

@model TestProject.ViewModels.MainLayoutData

@foreach (var type in Model.AllModuleTypes)
{
    <option>@type.something</option>
}

Solution

  • Since your class just exports a public static property, you are not able to access it from an instance. When using the @model directive you are expecting an instance of that class in the 'Model' property. Instead, use @using <name-space-name> to import the namespace where the class is and then you can access the static property directly MainLayoutData.AllModuleTypes.

    Take into account that you may not have a value set in that property. Make sure you have a value or validate before accessing it.

    @using TestProject.TheClassNamespace
    
    @foreach (var type in MainLayoutData.AllModuleTypes)
    {
        <option>@type.something</option>
    }