asp.net mvc返回加入的数据进行查看

时间:2011-12-14 16:26:06

标签: asp.net-mvc linq

我在返回要查看的数据时遇到问题。我想创建一个类似category->子类别的结构,当我尝试运行app时,不要编译。我有一个错误:

无法转换为'System.Collections.Generic.IEnumerable<字符串>到System.Collections.Generic.IEnumerable< mobile_store.Models.SubCategoryModel>

这是型号:

public class CategoryJoinModel
    {

        public string Category { get; set; }
        public List<SubCategoryModel> SubCategoryList {get; set;}
    }

第二个模型

public class SubCategoryModel
{
    public string SubCategory_Name { get; set; }
}

控制器

public ActionResult Index()
    {
        var joinedData = from c in db.category
                         from o in db.sub_category
                         where c.CAT_ID == o.CATEGORY_CAT_ID
                         select new
                         {
                             CategoryJoin = c.CAT_Name,
                             SubCatategoryJoin = o.SUBC_Name
                         };


        var gruped = from d in joinedData
                     group d by d.CategoryJoin
                     into g select new CategoryJoinModel
                     {
                         Category = g.Key,
                         SubCategoryList = new List<SubCategoryModel>(g.Select(s=>s.SubCatategoryJoin))
                     };
        return View(gruped.ToList());
    }

索引视图

    @model IEnumerable<mobile_store.Models.CategoryJoinModel>
    @helper DisplayCat(mobile_store.Models.CategoryJoinModel cat)
    {
  @Html.DisplayFor(model => cat.Category)
  <ul>
  @foreach (var item in cat.SubCategoryList)
  {
    @DisplaySubCat(item)
  }
  </ul>
}

@helper DisplaySubCat(mobile_store.Models.SubCategoryModel subCat)
    {
  <li>@MvcHtmlString.Create(subCat.SubCategory_Name)</li>
}

@foreach (var cat in Model)
{
  @DisplayCat(cat)
}

@if (Model.Count() == 0)
{
   <i>no categories</i>
}

请帮忙。

1 个答案:

答案 0 :(得分:0)

问题在于分配SubCategoryList属性。它必须是List<SubCategoryModel>

var gruped = 
    from d in joinedData.ToList()
    group d by d.CategoryJoin into g 
    select new CategoryJoinModel
    {
        Category = g.Key,
        SubCategoryList = g.Select(s => new SubCategoryModel 
        { 
            SubCategory_Name = s.SubCatategoryJoin 
        }).ToList()
    };