返回列表中的多个对象属性

时间:2014-07-18 08:15:54

标签: c# asp.net-mvc razor

我可以通过ViewBag.Categories将CategoryName字段返回到列表中。我还想返回CategoryId字段并使用它来动态构建类别详细信息视图URL

这是控制器动作:

public ActionResult Details(Item item)
{
    var db = new appContext();
    ViewBag.Item = item.ItemTitle;
    ViewBag.ItemLink = "http://localhost:4444/Items/Details/" + item.ItemId;
    ViewBag.Categories = new List<string>(item.Categories.Select(c => c.CategoryName));

    return View();
}

这是返回类别列表的视图:

@foreach (string category in ViewBag.Categories)
{
    <li>
        <a href="http://localhost:4444/Categories/Details/???">@category</a>
    </li>
}

如何返回CategoryId,如上所示?

4 个答案:

答案 0 :(得分:3)

使用自定义类来存储类别:

public class CategoryViewModel
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
}

像这样分配:

ViewBag.Categories = item.Categories
    .Select(c => 
        new CategoryViewModel 
        { 
            CategoryId = c.CategoryId, 
            CategoryName = c.CategoryName
        }).ToList();

在您看来,请使用它:

@foreach (CategoryViewModel category in ViewBag.Categories)
{
    <li>
        <a href="http://localhost:4444/Categories/Details/@category.CategoryId">@category.CategoryName</a>
    </li>
}

答案 1 :(得分:1)

您可以使用匿名类型来实现此目的:

public ActionResult Details(Item item)
{
    var db = new appContext();
    ViewBag.Item = item.ItemTitle;
    ViewBag.ItemLink = "http://.../Items/Details/" + item.ItemId;
    ViewBag.Categories = item.Categories.Select(c => new { c.CategoryName, c.CategoryId });

    return View();
}

然后在你看来:

@foreach (var category in ViewBag.Categories)
{
    <li>
        <a href="http://localhost:4444/Categories/Details/@(category.CategoryId)">@category.CategoryName</a>
    </li>
}

但是,您可能需要考虑使用强类型模型替换ViewBag。它提供了很多好处 - 包括IntelliSense支持。

答案 2 :(得分:1)

您可以使用:{/ p>而不是使用List<string>

List<Tuple<int, string>>

E.g。

ViewBag.Categories = item.Categories.Select(cat => 
       Tuple.Create(cat.CategoryID, cat.CategoryName)).ToList();

答案 3 :(得分:0)

定义这样的视图模型:

 public class CustomViewModel
    {
        public string Item { get; set; }
        public string Title { get; set; }
        public Categories Categories { get; set; }
    }

    public class Categories
    {
        public int Id { get; set; }
        public string CategoryName { get; set; }
    }

    public ActionResult Details(Item item)
    {
        var db = new appContext();
        var model = new CustomViewModel{
            Item = item.ItemTitle,
            ItemLink = "http://localhost:4444/Items/Details/" + item.ItemId,
            Categories = (item.Categories.Select(c => 
                new Categories{ Id = c.Id,CategoryName= c.CategoryName})).ToList()
        };
        return View(model);
    }
  

并查看如下:

   @model Categories
   @foreach (Categories category in Model.Categories)
    {
      <li>
        <a href="http://localhost:4444/Categories/Details/@category.CategoryId">@category.CategoryName</a>
     </li>
    }