select 在一个视图中使用两个模型按特定 ID 列出 - Asp.Net MVC Razor

select list by specific id using two models in one view- Asp.Net MVC Razor

public partial class Category
{
    public Category()
    {
        this.SubCategories = new HashSet<SubCategory>();
    }               
    public int Cat_id { get; set; }
    public string Cat_Name { get; set; }
    public string Cat_Desc { get; set; }                
    public virtual ICollection<SubCategory> SubCategories { get; set; }
}

public partial class SubCategory
{
    public int SubCat_id { get; set; }
    public byte SubCat_icon { get; set; }
    public string SubCat_Name { get; set; }
    public string SubCat_Desc { get; set; }
    public int Cat_id { get; set; }                 
    public virtual Category Category { get; set; }
}

控制器

public ActionResult Index()
{
    List<object> myModel = new List<object>();
    myModel.Add(db.Categories.ToList());
    myModel.Add(db.SubCategories.ToList());
    return View(myModel);
}

查看

@model IEnumerable<object>
@{
    List<ProjName.Models.Category> IstCategory = Model.ToList()[0] as List<ProjName.Models.Category>;
    List<ProjName.Models.SubCategory> IstSubCategory = Model.ToList()[1] as List<ProjName.Models.SubCategory>;        
}
<h1>Category</h1>
@foreach(var item in IstCategory)
{           
    <div>@item.Cat_Name</div><br />      
}
<hr />
<h1>SubCategory</h1>
@foreach(var item in IstSubCategory)
{     
    <div>@item.SubCat_Name</div><br />       
}    

如何在 foreach() 循环中传递 distinct/specific id 以及在列表中选择数据时的 where 条件?

您正在努力实现这一目标吗?每个类别都有其子类别列表。

<h1>Category</h1>
@foreach(var cat in IstCategory)
{           
   <div>@cat.Cat_Name</div><br />   

   <hr />
   <h1>SubCategory</h1>
   @foreach(var sub_cat in IstSubCategory.Where(s => s.Cat_id == cat.Cat_id))
   {      
     <div>@sub_cat.SubCat_Name</div><br />       
   }     
}