在 mvc5 中使用 ado.net 创建动态菜单

dynamic menu create using ado.net in mvc5

我想创建动态菜单,所以首先我创建了模型,在操作方法中我们从数据库中获取数据并添加到列表中 接下来我需要将列表填充到视图菜单中,这是我正在使用的 _layout 页面

@Html.ActionLink(item.LinkText,item.Actionname,item.routeValue)                            

public class Menu
{       
    public string LinkText { get; set; }
    public string Actionname { get; set; }
    public string routeValue { get; set; }
    public List<Menu> menu { get; set; }
}


public ActionResult Index()
{     
    List<Menu> mlist = new List<Menu>();
    //List<Menu> m = new List<Menu>();
    Menu m = new Menu();
    using (SqlConnection conn = new SqlConnection(Cstring))
    {
        conn.Open();
        SqlDataReader myReader = null;
        SqlCommand myCommand = new SqlCommand("SELECT  [TextLinkName],[ActionLinkName],[Routevalue]  FROM [MVCTESTING].[dbo].[tbl_MainMenu]", conn);
        myReader = myCommand.ExecuteReader();

        while (myReader.Read())
        {

            m.LinkText = (string)myReader["TextLinkName"];
            m.Actionname = (string)myReader["ActionLinkName"];
            m.routeValue = (string)myReader["Routevalue"];
            mlist.Add(m);
        }

    }
    return View(mlist);

   // return View();
}
<ul class="dropdown">
          @if (Model != null)
          {
             foreach (var item in Model.menu)
                {
                    @Html.ActionLink(item.LinkText,item.Actionname,item.routeValue)
                }
             }
        </ul>

我遇到的错误

错误:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[WebApplication1.Models.Menu]', but this dictionary requires a model item of type 'WebApplication1.Models.Menu'.

你的后端没问题,但是页面顶部的类型是错误的,因为你传递的是菜单列表,你应该在页面_layout 上收到相同的内容,只需添加以下行:

@model List<WebApplication1.Models.Menu>