【问题标题】:select list by specific id using two models in one view- Asp.Net MVC Razor在一个视图中使用两个模型按特定 ID 选择列表-Asp.Net MVC Razor
【发布时间】:2016-01-11 10:24:21
【问题描述】:

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() 循环中传递不同/特定的 id 以及 where 条件?

【问题讨论】:

    标签: asp.net asp.net-mvc relationship


    【解决方案1】:

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

    <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 />       
       }     
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 2017-01-15
      • 2021-03-17
      相关资源
      最近更新 更多