Click here to Skip to main content
15,301,414 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to programming with MVC.I created an accordion menu with Partial View and rendered it in Layout.cshtml. When I run the program at the beginning, the accordion menu appears, but if I link to another page with the submenu, it gives the above error.

What I have tried:

layout.cshtml:
HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="~/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
    @{ Html.RenderPartial("_myprg");  }

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>© @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    @RenderSection("scripts", required: false)
</body>
</html>

_myprg.cshtml:
Razor
@model layoutmenu.Models.MenuModel

<link href="Css/styles.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $("#accordian h3").click(function () {
            $("#accordian ul ul").slideUp();
            if (!$(this).next().is(":visible")) {
                $(this).next().slideDown();
            }
        });
    });
</script>


@using (Html.BeginForm("Index", "Home"))
{

    <div id="accordian" dir="rtl">
        <ul>
            <li>
                @{
    foreach (var MenuItem in Model.MainMenuModel)
    {

        var SubMenuItem = Model.SubMenuModel.Where(m => m.MainMenuID == MenuItem.ID);

        <h3><a href="@MenuItem.MainMenuURL"> @MenuItem.MainMenuItem </a></h3>

        if (SubMenuItem.Count() > 0)
        {
            <ul>
                @foreach (var SubItem in SubMenuItem)
                {
                    <li><a href='@SubItem.SubMenuURL'>@SubItem.SubMenuItem</a></li>
                }
            </ul>
        }

    }
                }
        </ul>
    </div>
}


class:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace layoutmenu.Models
{
    public class Custem
    {
        public int ID { get; set; }
        public int code { get; set; }
        public string peaces { get; set; }
    }
}
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Mvc;

namespace layoutmenu.Models
{
    public class custemdb
    {
        private SqlConnection con;

        private void connection()
        {

            
            string constring = ConfigurationManager.ConnectionStrings["customer"].ToString();
            con = new SqlConnection(constring);
        }
        public List<Custem> GetItemList()
        {

            connection();
            List<Custem> iList = new List<Custem>();

            string query = "SELECT * FROM peace";
            SqlCommand cmd = new SqlCommand(query, con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();

            con.Open();
            adapter.Fill(dt);
            con.Close();

            foreach (DataRow dr in dt.Rows)
            {
                iList.Add(new Custem
                {
                    ID = Convert.ToInt32(dr["ID"]),
                    code = Convert.ToInt32(dr["code"]),
                    peaces = Convert.ToString(dr["peaces"]),

                });
            }
            return iList;
        }
        public bool InsertItem(Custem iList)
        {
            connection();
            
           
            string query = "INSERT INTO peace VALUES('" + iList.code + "','" + iList.peaces + "')";
           
            SqlCommand cmd = new SqlCommand(query, con);
            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();

            if (i >= 1)
                return true;
            else
                return false;
           
        }

        public bool UpdateItem(Custem iList)
        {
            connection();
            string query = "UPDATE peace SET code = '" + iList.code + "', peaces = '" + iList.peaces + " WHERE ID = " + iList.ID;
            SqlCommand cmd = new SqlCommand(query, con);
            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();

            if (i >= 1)
                return true;
            else
                return false;
        }

        // 4. ********** Delete Item **********
        public bool DeleteItem(int id)
        {
            connection();
            string query = "DELETE FROM peace WHERE ID = " + id;
            SqlCommand cmd = new SqlCommand(query, con);
            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();

            if (i >= 1)
                return true;
            else
                return false;
        }
    }
}

index.cshtml
Razor
@model IEnumerable<layoutmenu.Models.Custem>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
           
            @Html.DisplayNameFor(model => model.First().code)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.First().peaces)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
           
            @Html.DisplayFor(modelItem => item.code)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.peaces)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>

custem controller:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using layoutmenu.Models;

namespace layoutmenu.Controllers
{
    public class custemController : Controller
    {
        //
        // GET: /custem/
        public ActionResult Index()
        {
            custemdb dbcust = new custemdb();
            ModelState.Clear();
            return View(dbcust.GetItemList());
        }

        //
        // GET: /custem/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /custem/Create
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /custem/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /custem/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /custem/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /custem/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /custem/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

Homecontroller
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using layoutmenu.Models;

namespace layoutmenu.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            MenuModel ObjMenuModel = new MenuModel();
            ObjMenuModel.MainMenuModel = new List<MainMenu>();
            ObjMenuModel.MainMenuModel = GetMainMenu();
            ObjMenuModel.SubMenuModel = new List<SubMenu>();
            ObjMenuModel.SubMenuModel = GetSubMenu();

            return View(ObjMenuModel);
        }
       
       
        public List<MainMenu> GetMainMenu()
        {
            List<MainMenu> ObjMainMenu = new List<MainMenu>();
            List<MainMenu> obj1 = new List<MainMenu>();
            ObjMainMenu.Add(new MainMenu { ID = 1, MainMenuItem = "ورزشی", MainMenuURL = "#" });
            ObjMainMenu.Add(new MainMenu { ID = 2, MainMenuItem = "هنری", MainMenuURL = "#" });
            ObjMainMenu.Add(new MainMenu { ID = 3, MainMenuItem = "فرهنگی", MainMenuURL = "#" });
            ObjMainMenu.Add(new MainMenu { ID = 4, MainMenuItem = "اقتصادی", MainMenuURL = "#" });
            obj1.Add(new MainMenu { ID = 1, MainMenuItem = "3ورزشی", MainMenuURL = "#" });

            return ObjMainMenu;
        }
        public List<SubMenu> GetSubMenu()
        {
            List<SubMenu> ObjSubMenu = new List<SubMenu>();
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "کفش ورزشی", SubMenuURL = "http://localhost:51729/custem/Index" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "ساک ورزشی", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "ابزار ورزشی", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "لباس ورزشی", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 2, SubMenuItem = "کفش ورزشی", SubMenuURL = "http://localhost:51729/custem/Create" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 2, SubMenuItem = "ساک ورزشی", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 2, SubMenuItem = "ابزار ورزشی", SubMenuURL = "#" });
            ObjSubMenu.Add(new SubMenu { MainMenuID = 2, SubMenuItem = "لباس ورزشی", SubMenuURL = "#" });
            return ObjSubMenu;
        }

       
    }
}
Posted
Updated 8-Dec-21 22:24pm
v2
Comments
Richard Deeming 9-Dec-21 4:25am
   
Beyond that, you've not provided the full error message, nor told us where the error occurs.
Mohamad Hossiny 9-Dec-21 14:51pm
   
The acordion menu appears when I run the program, but when I click on this submenu: ObjSubMenu.Add(new SubMenu { MainMenuID = 1, SubMenuItem = "کفش ورزشی", SubMenuURL = "http://localhost:51729/custem/Index" });
This line in Layout.cshtml (@{ Html.RenderPartial("_myprg"); }) gives the following error :
{"The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[layoutmenu.Models.Custem]', but this dictionary requires a model item of type 'layoutmenu.Models.MenuModel'."}

The table list should be displayed in custom / index, but the program will stop.
j snooze 9-Dec-21 17:42pm
   
How come on the RenderPartial you are not passing in a model to the view? Its expecting a view object of MenuModel as evidenced in the partial view code at the very top line of _myprt.cshtml.
@model layoutmenu.Models.MenuModel

Mohamad Hossiny 10-Dec-21 8:28am
   
My problem is that I want to create a accordian menu in Layout.cshtml and show it in all views and connect to create, delete, ... with submenu, but I can not. Thank you all very much for your answer.
If possible, guide me step by step because I am a beginner.
Can anyone guide me?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900