从 _layout.cshtml 访问模型 属性 时出现问题

problem to access a model property from _layout.cshtml

检查下面的代码。我正在使用 c# mvc5 并尝试从 _Layout.cshtml 循环模型,但是当我尝试从模型 MainLayoutData visual studio 访问 AllModuleTypes 属性 时,intellisense 显示错误: member cannot be accessed with an instance reference qualify it with a type name instead。我做错了什么?

型号:

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

控制器:

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>
}

由于您的 class 仅导出 public static 属性,您无法从实例访问它。当使用 @model 指令时,您期望在 'Model' 属性 中有一个 class 的实例。相反,使用 @using <name-space-name> 导入 class 所在的命名空间,然后您可以直接访问静态 属性 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>
}