How to display categories in a database in SQL Server in _Layout.cshtml

I am trying to show categories in my database on SQL

my homepage , how do I do this? I have this in my : MVC web

_Layout.cshtml

<div class="list-group">
                    <a href="#" class="list-group-item">Category 1</a>
                    <a href="#" class="list-group-item">Category 2</a>
                    <a href="#" class="list-group-item">Category 3</a>
                </div>

      

this is mine Views/store/index.cshtml

:

@model IEnumerable<MVCOnlineShop.Models.Category>

@{
    ViewBag.Title = "Store";
}
<h3>Browse Categories</h3>
<p>
    Select from @Model.Count()
    Categories:
</p>
<ul>
    @foreach (var Category in Model)
    {

        <li>
            @Html.ActionLink(Category.CategoryName,
"Browse", new { Category = Category.CategoryName })
    </li>
    }
</ul>

      

this is mine StoreController

:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCOnlineShop.Models;

namespace MVCOnlineShop.Controllers
{
    public class StoreController : Controller
    {
        OnlineStoreEntities storeDB = new OnlineStoreEntities();
        //
        // GET: /Store/

        public ActionResult Index()
        {
            var Categories = storeDB.Categories.ToList();
            return View(Categories);
        }
        //
        // GET: /Store/Browse
        public ActionResult Browse(string Category)
        {
            // Retrieve Category and its Associated Products from database
            var CategoryModel = storeDB.Categories.Include("Products")
                .Single(g => g.CategoryName == Category);

            return View(CategoryModel);
        }
        //
        // GET: /Store/Details
        public ActionResult Details(int id)
        {
            var Product = storeDB.Products.Find(id);

            return View(Product);
        }
        //
        // GET: /Store/Browse?Category=Games

    }
}

      

and this is mine Global.asax

:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MVCOnlineShop
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {


            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }
}

      

+3


source to share


2 answers


One way to do what you want to do is to use Session var.

In Global.asax.cs :

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();
    }

    protected void Session_Start()
    {
        // 'using' will call entity.Dispose() at the end of the block so you
        // don't have to bother about disposing your entity
        using(OnlineStoreEntities entity = new OnlineStoreEntities()){
            HttpContext context = HttpContext.Current;
            if(context != null && context.Session != null)
                // fill the Session var with the Categories from your database
                context.Session["Categories"] = entity.Categories.ToList();
        }
    }
}

      

In _layout.cshtml :

@using MVCOnlineShop.Models;

@*[anything you want here]*@

@{
    // stores the Session content in a var
    var Categories = Session["Categories"] as List<Category>;
}

@*Checks if the Session variable is correct*@
@if(Categories != null){
    <ul>
        @*For each category in the Session var, display the link*@
        @foreach(var Category in Categories){
            <li>
                @Html.ActionLink(Category.CategoryName, "Browse", new { Category = Category.CategoryName })
            </li>
        }
    </ul>
}

      


A bit of explanation:

A session variable is a variable that is accessible from anywhere in the application until it expires.

The default duration for a session variable is 20 minutes, which means that if you are browsing your application and remain inactive for 20 minutes, all session sessions will be lost. This duration can be customized.



The method Session_Start

in Global.asax is called once the first time the application is accessed and after the session state has been declared / available. I believe this is the first place where you can set session variables, so we populate it with the required data in the Categories index.

Session["Categories"] = entity.Categories.ToList();

      

Since the session variables are available from anywhere in your application, we then access it in your _layout.cshtml so that we can display each Category

of the list.

Session variables can be stored by anyone Object

, so we need to explicitly specify the value when we manipulate it.

List<Category> Categories = Session["Categories"] as List<Category>;

      

We then check if the casting succeeded with if(Categories != null)

.

It works? We can then iterate over this list:

@foreach(Category category in Categories){}

      

+2


source


So, you can do the following:

Create a Categories control and add the following lines of codes which get your categories from the database or somewhere else.

Create class as following for category

public class CategoryViewModel
{
    public int CategoryId {get;set;}
    public string CategoryName {get;set;}
}

      

You can use the following dummy data binding method.

[HttpGet]
public ActionResult BlogCategories()
{
    List<CategoryViewModel> model= new List<CategoryViewModel>();
    model.Add(new CategoryViewModel(){CategoryId=1,CategoryName="AA"});
    model.Add(new CategoryViewModel(){CategoryId=2,CategoryName="BB"});
    model.Add(new CategoryViewModel(){CategoryId=3,CategoryName="CC"});
    model.Add(new CategoryViewModel(){CategoryId=4,CategoryName="DD"});
    return PartialView("BlogCategories",model);
}

      



and create a partial view that will display the category data.

@model List<DotnetTutorial.Data.ViewModel.CategoryViewModel>

@foreach (var item in Model)
{
       <div class="categoryLi">
            @Html.RouteLink(item.CategoryName, "ArticlesCategoryList")
        </div>        
}

      

and finally, you can simply call this partial view on your home page using the following line of code.

@Html.Action("BlogCategories", "Categories")

      

Hope this helps you.

0


source







All Articles