如何在MVC中的_Layout.cshtml中显示SQL数据库中的数据
我正在从事一个MVC OnlineShop项目,我在如何在MVC中的_Layout.cshtml中显示SQL数据库中的数据,html,asp.net-mvc,twitter-bootstrap,layout,partial-views,Html,Asp.net Mvc,Twitter Bootstrap,Layout,Partial Views,我正在从事一个MVC OnlineShop项目,我在SQL server中创建了类别和产品数据库,现在我想在web主页上显示该数据库中的类别。在创建会话并在\u Layout.cshtml中调用此会话之前,我尝试过,但我发现会话虽然有效,但在主页上显示类别并不是一个好主意,因为会话主要用于cookie。。。 问题:这是正确的方法还是更好的方法? 我在我的Homecontroller.cs中写了这个: using System; using System.Collections.Generic;
SQL server
中创建了类别和产品数据库,现在我想在web主页上显示该数据库中的类别。在创建会话并在\u Layout.cshtml
中调用此会话之前,我尝试过,但我发现会话虽然有效,但在主页上显示类别并不是一个好主意,因为会话主要用于cookie。。。
问题:这是正确的方法还是更好的方法?
我在我的Homecontroller.cs
中写了这个:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCOnlineShop.Models;
namespace MVCOnlineShop.Controllers
{
public class HomeController : Controller
{
OnlineStoreEntities storeDB = new OnlineStoreEntities();
//
// GET: /Home/
public ActionResult Index()
{
var Categories = storeDB.Categories.ToList();
return View(Categories);
}
//
// GET: /Home/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: /Home/Details
public ActionResult Details(int id)
{
var Product = storeDB.Products.Find(id);
return View(Product);
}
//
// GET: /Home/Browse?Category=Games
}
}
并在Views/Home
中创建了一个名为CategoryLayout.cshtml
的PartialView:
@model IEnumerable<MVCOnlineShop.Models.Category>
@{
ViewBag.Title = "Categories";
}
<ul>
@foreach (var Category in Model)
{
<li>
@Html.ActionLink(Category.CategoryName,
"Browse", new { Category = Category.CategoryName })
</li>
}
</ul>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<div class="dropdown">
<button class="dropbtn">@Html.Partial("CategoryLayout")</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
</ul>
}
首先
编辑
public ActionResult GetCategories ()
{
var Categories = storeDB.Categories.ToList();
return PartialView("CategoryLayout",Categories );
}
上述代码将使用类别模型呈现局部视图,并将发送回布局视图
@Html.Partial("CategoryLayout")
使用
完成 显示您的代码。如果类别不打算更改,您可以将它们缓存在应用程序状态中,该状态保留在服务器端。请看@Reshma我编辑并添加了一些代码check@BarryO“凯恩类别可能会在以后更改,因此我想从SQL Server收集数据。您的代码很好。我怀疑这些类别很少发生更改,因此,如果要缓存它们,我建议再次将它们存储在应用程序状态。
@Html.RenderAction("GetCategories","Home")