打印出来class属性查看

Print out class property to view

正在尝试将 属性 的虚拟列表打印到我的视图中。不确定是否访问错误或者我的数据库结构不正确。

我的模特:

public class Deck
{
    public int id { get; set; }

    public string Name { get; set; }

    public string Notes { get; set; }
    [DisplayName("Card")]
    public virtual List<Card> Card { get; set; }
}

public class Card
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? Atk { get; set; }
    public int? Def { get; set; }
    public string Desc {get; set;}
    public int? Level { get; set; }
    public string Type { get; set; }
    public string Attribute { get; set; }
    [DisplayName("Image")]
    public virtual List<Image> Card_Images { get; set; }

    public virtual List<Deck> Deck { get; set; }


}

public class Image
{
    public int Id { get; set; }
    public string image_url { get; set; }
    public string image_url_small{ get; set;  }
}

我的控制器操作:

    public ActionResult Details(int id)
    {

        var deck = _context.Decks.SingleOrDefault(d => d.id == id);

        if (deck == null)
            return HttpNotFound();

        return View("Details");
    }

我的看法:

@model YGOBuilder.Models.Deck

<div>
    <h4>Deck</h4>
    <hr />
    <dl class="dl-horizontal">
        <dd>
            @foreach (var m in Model.Card)
            {
                foreach (var card in m.Card_Images)
                {
                    <td>
                    <img src=@card.image_url height="300" width="200">
                    </td>
                }
            }
        </dd>

    </dl>
</div>
<p>
    @Html.ActionLink("Decks", "Index")
</p>

我试过摆弄 foreach 循环,尝试不同的访问方法,但似乎都在

上出错了
@foreach (var m in Model.Card)

并抛出 'Object reference not set to an instance of an object.'

您收到 null reference 异常,因为您的 Model 为空。您需要将模型传递给您的视图。 由于您的 viewaction 名称相同,您可以 return 使用 model 的视图] 像这样:return View(deck);

public ActionResult Details(int id)
{

    var deck = _context.Decks.SingleOrDefault(d => d.id == id);

    if (deck == null)
        return HttpNotFound();

    return View(deck);
}