编辑基于用户评论,他想在加载时绑定数据,制作嵌套列表,我会留下我的旧答案,因为它可能对其他人有帮助,我也会添加新答案,
我的建议是您将行业列表作为 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);
}
ajax 代码
// 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));
});
});
});
我希望这回答了你的问题,我不确定你所说的实体框架不同是什么意思,你可以问我更具体的问题也许我可以帮助