0

I want to create dynamic menu, so first i have created model and in the action method we have fetch data from the database and add into the list next i need populate list into the view menu and this is my _layout page which i am using

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

error i am facing

Error:

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'.

bommelding
  • 2,969
  • 9
  • 14
ashish
  • 3
  • 3
  • The error is quite clear but you did not post the line it refers to. Look at the very top of your _layout.cshtml. The type there has to match what you put into `return View(...);` – bommelding Jan 31 '19 at 10:57
  • [similar issue](https://www.c-sharpcorner.com/UploadFile/97fc7a/dictionary-requires-a-model-item-of-type-system-collections/) was fixed. – Gowtham Alan Jan 31 '19 at 11:00
  • 1
    Possible duplicate of [The model item passed into the dictionary is of type .. but this dictionary requires a model item of type](https://stackoverflow.com/questions/40373595/the-model-item-passed-into-the-dictionary-is-of-type-but-this-dictionary-requ) – Tetsuya Yamamoto Feb 01 '19 at 01:54

1 Answers1

0

your backend is ok, but the type that is at the top of your page is wrong, as you are passing a list of menus, you should receive the same on your page _layout, just add the line:

@model List<WebApplication1.Models.Menu>
Cassio Alves
  • 116
  • 3