如何从ASP.NET Core RazorPages中的appsettings.json在Razor视图中显示菜单数组

时间:2018-10-08 10:39:24

标签: c# json razor asp.net-core-mvc razor-pages

如何在ASP.NET Core RazorPages中的appsettings.json中在Razor View中显示菜单数组,我在这里停留了几天。任何人都可以给我解决方案吗?

public void OnGet()
{
    ViewData["Test"] = Test().AsEnumerable();
}

public class AppMenu
{
    public string MenuName { get; set; } // Module Name
    public List<AppMenu> MenuList { get; set; } = new List<AppMenu>();
}

public string Test()
{
    var apps = new List<AppMenu>();
    List<string[]> listMenus = new List<string[]>();
    var hpMenu = new[] { "xxx", "xxx", "xxx", "xxx", "xxx" };
    var vtMenu = new[] { "yyy", "yyy", "yyy", "yyy", "yyy" };
    var purAgr = new[] { "zzz", "zzz", "zzz" };
    var mainManu = new[] { "aaa", "aaa"};
    listMenus.Add(hpMenu);
    listMenus.Add(vtMenu);
    // listMenus.Add(hpMenu)
    foreach (var main in mainManu)
    {
        AppMenu appmainmenu = new AppMenu();
        appmainmenu.MenuName = main;
        apps.Add(appmainmenu);
    }
    for (var i = 0; i <= listMenus.Count - 1; i++)
    {
        List<AppMenu> lsmenu = new List<AppMenu>();
        foreach (var menustr in listMenus[i])
        {
            AppMenu appmenu = new AppMenu();
            appmenu.MenuName = menustr;
            if (menustr == "Purchase Agreement")
            {
                foreach (var it in purAgr)
                {
                    AppMenu purr = new AppMenu();
                    purr.MenuName = it;
                    appmenu.MenuList.Add(purr);
                }
            }
            lsmenu.Add(appmenu);
        }
        apps[i].MenuList = lsmenu;
    }
    return JsonConvert.SerializeObject(apps);
}

任何人都可以帮助我显示菜单,类似这样。 Index.cshtml(例如)

@foreach (var test in ViewData["Test"])
{
    <p>@test</p>
}

1 个答案:

答案 0 :(得分:0)

我不确定,您到底想做什么,以及为什么要将JsonString转换为可枚举。

如果您在视图中需要这些类,则可以通过在模型中定义菜单列表来使用它们:

public List<AppMenu> AppMenues;
public void OnGet()
{
    AppMenues = Test();
}

在您的Test函数中,您应该只返回您正在创建的列表。我将使用您的函数名称,但您应该将其重命名:

public List<AppMenu> Test()
{
    var apps = new List<AppMenu>();
    //your filling logic
    return apps;
}

现在您可以在RazorPage中使用它:

@page
@model HomeModel
@{
    foreach (var i in Model.AppMenues)
    {
        <p>@i.MenuName</p>
    }
}

如果您不在名为home的页面上,则模型名称应该不同。