【问题标题】:Dealing with multiple models for specific attributes of each in view针对每个视图的特定属性处理多个模型
【发布时间】:2015-06-30 19:37:21
【问题描述】:

我试图在表格中显示一组特定于 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>

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

【问题讨论】:

    标签: c# asp.net-mvc ienumerable


    【解决方案1】:

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

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

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

    【讨论】:

    • ViewBag 也可以工作吗?对不起..我对此很陌生。
    • 是的,我想如果您想将模型传回视图包中,然后将该视图包投射到您的视图中,那将可行。但是,正确的方法和公认的最佳实践是使用视图模型来处理服务器端代码和视图表单之间的交互。
    • 我的意思是......因为我只想公开 Deck 模型的 1 个特定属性( Name ),仅此而已。
    猜你喜欢
    • 1970-01-01
    • 2018-06-25
    • 2012-03-13
    • 2019-10-03
    • 2022-07-13
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多