Pages

Thursday, 4 November 2021

Fill Menu items in partial view from database without using java script in C# ASP.NET MVC

 Fill Menu items in partial view from the database without using javascript in C# ASP.NET MVC.

Menu items from database


When there is a need to load menu items from the database, then you may have many options like load it from javascript. But the best load time is when you use Razor collaborate with C#. This post will help you to do the same. Follow the step-by-step instructions. I Guarantee that response time is the lowest than any other approach. 

Model

public class MenuModel

{

   public string ID { get; set; }

   public string MenuName { get; set; }

}

Controller

public ActionResult MenuLayout()
{

     List<MenuModel> menu = new List<MenuModel>();
     SelectRepository ob = new SelectRepository();
    // _MenuWebsite is a partial view which will render menu object
     menu = ob.GetMenuCategory();
     return PartialView("_MenuWebsite", menu);

 }


Repository

public List<MenuModel> GetMenuCategory()
{

     List<MenuModel> Record = new List<MenuModel>();
     try
     {
        using (OleDbConnection dbcon = new OleDbConnection(db.getConstr()))

        {

            string sql = "SELECT CatagoryMaster.ID, CatagoryMaster.Catagory FROM CatagoryMaster where CatagoryMaster.active=1";
            using (OleDbCommand cmd = new OleDbCommand(sql, dbcon))

            {

                  if (dbcon.State == ConnectionState.Closed)
                     dbcon.Open();
                 using (OleDbDataReader drOb = cmd.ExecuteReader())
                 {

                     if (drOb.HasRows)
                     {

                         while (drOb.Read())
                         {

                             MenuModel data = new MenuModel();
                             data.ID = drOb.IsDBNull(0) ? " " : Convert.ToString(drOb[0]);
                             data.MenuName = drOb.IsDBNull(1) ? " " : Convert.ToString(drOb[1]);

                             Record.Add(data);

                          }

                      }

                   }

               }

           }

      }

      catch (Exception ex)
      {

          //ErrMsg = ex.Message;
      }

      return Record;

  }


Layout Code

@Html.Action("MenuLayout", "common")


_MenuWebsite Code


@model banarsisale.Models.MenuBunchModel

 <ul class="depart-hover">
         @foreach(var item in Model.Menu1)
          {
                   <li><a href="#">@item.MenuName</a></li>
           }
  </ul>


Next Topic

No comments:

Post a Comment