gpt4 book ai didi

c# - Action 链接到另一个 View (MVC)

转载 作者:行者123 更新时间:2023-11-28 00:55:22 25 4
gpt4 key购买 nike

我正在处理我的MVCOnlineShop 项目,我通过创建部分 View 在主页上显示类别 CategoryLayout.cshtml :

@model IEnumerable<MVCOnlineShop.Models.Category>
@{
ViewBag.Title = "CategoryLayout";
}
<ul class="nav navbar-nav">
@foreach (var Category in Model)
{
<li>
@Html.ActionLink(Category.CategoryName,
"ProductList", new { Category = Category.CategoryName })
</li>

</ul>

并在 _Layout.cshtml 中添加:

@Html.Partial("CategoryLayout")

现在我想按主页上的任何类别,它将带我到此类别的产品,我创建了这个部分 View ProductList.cshtml :

@model MVCOnlineShop.Models.Category

@{
ViewBag.Title = "ProductList";
}
<ul>

@foreach (var Product in Model.Products)
{
<li>
@Html.ActionLink(Product.ProductName,
"Details", new { id = Product.CategoryID })
</li>
}
</ul>

这是我的HomeController:

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

public ActionResult CategoryLayout()
{
var Categories = storeDB.Categories.ToList();
return PartialView("CategoryLayout", Categories);
}

}
}

问题:我怎样才能在主页上点击一个类别,这将带我到一个显示该类别产品的页面,我该怎么做?

提前致谢:)

最佳答案

开始吧:

首先您的操作链接应该是:

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

然后您必须在您的 Controller 中添加 ProductList 操作,例如:

public ActionResult ProductList(int? CategoryId)
{
Category objCategory = new Category();

objCategory.Products = storeDB.Products.where(m => m.CategoryId == CategoryId).ToList();

return PartialView("ProductList", objCategory);
}

您的产品局部 View 应该是:

@model MVCOnlineShop.Models.Category 

@{
ViewBag.Title = "ProductList";
}
<ul>

@foreach (var Product in Model.Products)
{
<li>
@Html.ActionLink(Product.ProductName,
"Details", new { id = Product.CategoryID })
</li>
}
</ul>

干杯!!

关于c# - Action 链接到另一个 View (MVC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45213504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com