public class ItemController : Controller
{
private readonly ApplicationDbContext _context;
public ItemController(ApplicationDbContext context)
{
_context = context;
}
public ActionResult GetItemsByCategoryId(int categoryId)
{
var items = _context.Items.Where(x => x.CategoryId == categoryId).ToList();
return View(items);
}
}
@model List-
@foreach(var item in Model)
{
@item.Name
}
routes.MapRoute(
name: "GetItemsByCategory",
url: "get-items-by-category/{categoryId}",
defaults: new { controller = "Item", action = "GetItemsByCategoryId", categoryId = UrlParameter.Optional }
);
此路由将处理从其他模型中获取项列表的请求,并在控制器方法中使用传递的类别ID来检索匹配的项目。
您可以根据需要更改路由的名称和URL。此外,请注意,示例控制器采用了Entity Framework,因此您需要使用自己的ORM或DAO库进行 ORM / DAO 操作。