针对每个视图的特定属性处理多个模型

Dealing with multiple models for specific attributes of each in view

我正在尝试在 table 中显示一组特定于 n 个模型中每个模型的属性

我有以下型号:

卡片

public enum Rarity
{
    Legendary,
    Epic,
    Rare,
    Common
}

public class Card
{
    public int ID { get; set; }

    public string Name { get; set; }
    public bool Disenchant { get; set; }
    public Rarity Rarity { get; set; }

    public virtual ICollection<Deck> Decks { get; set; }
}

甲板

public class Deck
{
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual Card Card { get; set; }
    public virtual Hero Hero { get; set; }
}

首页控制器索引:

public ActionResult Index()
{
    var db = new DustContext();
    var cards = db.Cards.ToList();
    return View(cards);
}

索引片段:

@model IEnumerable<App.Models.Card>
<tbody>
  @foreach (var item in Model)
  {
    @Html.Partial("_CardList", item)
    }
</tbody>

最后是我的部分:

@model CardApp.Models.Card

<tr>
  <td>@Model.Name</td>
  <td>@Model.Rarity</td>
  <td>@Model.Disenchant</td>
</tr>

如何在 table 中显示卡片模型(已经在部分中)的属性以及 Deck 模型的 属性?我试过使用元组,但出现了 List 和 IEnumerable 错误。

您应该使用 ViewModel 并在 ViewModel 中拥有每个模型的实例。

基本上,您的 ViewModel 将是您传递给视图的内容,其中包含任意数量的其他对象、模型、属性等。

http://sampathloku.blogspot.com/2012/10/how-to-use-viewmodel-with-aspnet-mvc.html