我在数据库行业和类别中有 2 个表。它们在表中使用 IndustryId 作为主键和外键进行连接。现在我想将 Industry 显示为我的主菜单项,将相关类别显示为我各自行业的子菜单项。我正在使用 asp net mvc enity 框架作为我与 Visual Studio 2017 的编码架构。这是我在这个架构上的第一个应用程序,我想要一个简单的解释,包括模型视图和控制器一步一步。我之前已经在 asp net web 表单上完成了这个绑定没有 mvc。但是实体框架似乎与以前的版本完全不同。
根据用户评论进行编辑,他想在加载时绑定数据,制作嵌套列表,我会留下我的旧答案,因为它可能会帮助其他人,我也会添加新答案,我的建议是您将行业列表传递为一个 ViewBag,因为在与行业表相关的行业 ID 的类别中有外键,ef 将检测该关系并将其表示在您的行业模型中virtual Collection<Category> Categories
,这表示与该行业相关的所有类别。你可以做的是传递它然后使用剃刀语法在你的控制器的视图中做这样的事情你将它作为viewbag传递
ViewBag.Industries = dbContext.Industries.Include(x => x.Categories).ToList();
那么在你看来
<!-- init your list -->
<ul>
<!-- loop through your viewbag -->
foreach (var x in (List<Industry>) ViewBag.Industries)
{
<li> x.IndustryName
<!-- init your sub menu -->
<ul>
<!-- loop through your categories of this industry x -->
foreach(var c in x.Categories)
{
<li> c.CategoryName </li>
}
</ul>
</li>
}
<!-- loop end, close your list -->
</ul>
对于希望根据另一个菜单值动态更新菜单内容的人,请阅读以下内容:
我解决这个问题的方法是,首先创建接受行业ID并返回列表或类别的操作,每当我的行业ID列表在前端(更改事件侦听器)发生变化时,我都会使用ajax调用此操作,然后将返回作为对象列表,使用 jquery 将数据绑定到我的子菜单。就像是
public ActionResult GetCategories(int IndustryID)
{
// this simple select query, retrieves all categories that have industry id provided
var categories = dbContext.Categories.Where(c => c.IndustryId == IndustryID).ToList();
return Json(categories);
}
阿贾克斯代码
// industryId is the id of industry in your view, apply change event listener
$('#industryId').change(function () {
// ajax call, get data
$.ajax({
type: "POST",
url: '@Url.Action("GetCategories", "controllerhere")',
data: { IndustryID: this.value},
dataType: "json"
}).done(function(data){
// Data recieved, get categories list, empty it, bind the new data
var ddl = $("#categoriesList");
ddl.empty();
ddl.append($('<option>', {value: 0,text: 'Select'})); //Newly added
// categoryID and CategoryName are properties in your category, these Names I assumed, they might change depending on your Model
$.each(data, function () {
ddl.append($('<option></option>').attr("value", this.CategoryID).text(this.CategoryName));
});
});
});
我希望这回答了您的问题,我不确定您所说的实体框架不同是什么意思,您可以问我更具体的问题,也许我可以提供帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句