ASP.Net MVC:为什么我的内联 html 助手不打印任何内容



我想用我的内联html助手用ul/li构建UI,但是当我运行我的程序时,它没有打印任何东西。

查看我的代码

@helper ShowTree(List<Scaffolding.Controllers.MenuItem> menusList)
{
    <ul>
        @foreach (var item in menusList)
        {
            <li>
                <span>@item.Name</span>
                @if (item.Children.Any())
                {
                    @ShowTree(item.Children)
                }
            </li>
        }
    </ul>
}
@{
    var menuList = ViewBag.menusList as List<Scaffolding.Controllers.MenuItem>;
    ShowTree(menuList);
}

服务器端操作代码

public ActionResult Index()
{
    List<MenuItem> allMenu = new List<MenuItem>
    {
    new MenuItem {Id=1,Name="Parent 1", ParentId=0},
    new MenuItem {Id=2,Name="child 1", ParentId=1},
    new MenuItem {Id=3,Name="child 2", ParentId=1},
    new MenuItem {Id=4,Name="child 3", ParentId=1},
    new MenuItem {Id=5,Name="Parent 2", ParentId=0},
    new MenuItem {Id=6,Name="child 4", ParentId=4}
    };
    List<MenuItem> mi = allMenu
    .Where(e => e.ParentId == 0) /* grab only the root parent nodes */
    .Select(e => new MenuItem
    {
    Id = e.Id,
    Name = e.Name,
    ParentId = e.ParentId,
    Children = allMenu.Where(x => x.ParentId == e.Id).ToList()
    }).ToList();
    ViewBag.menusList = mi;
    return View();
}

波科类

public class MenuItem 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ParentId { get; set; }
    public virtual List<MenuItem> Children { get; set; }
}

我的 Razor 视图代码中有什么问题,没有打印任何内容。 请给我一些提示以找出错误。 谢谢

您应该尝试以下更正:

@{
    var menuList = ViewBag.menusList as List<Scaffolding.Controllers.MenuItem>;
    @ShowTree(menuList);
}
如果您希望代码在

页面上输出 html,则需要在代码语法的前缀中包含 @,即 @row.id@mystring@Html.Raw("<p>hello</p>")

最新更新