【问题标题】:How to display data from 2 tables in the same list view in MVC?如何在 MVC 的同一个列表视图中显示 2 个表中的数据?
【发布时间】:2015-08-11 04:03:16
【问题描述】:

我已经能够根据控制器中的以下 SQL 查询从我想要的卡表中取回数据:

SQLstatement = string.Format("select * from cards, cardcollections where isowned = 1 and cards.cardid = cardcollections.cardid and collectionid = {0}", v.CollectionID);
var CardList = db.Cards.SqlQuery(SQLstatement);
return View(CardList.ToPagedList(pageNumber, pageSize));

如果我只引用 Cards 模型,它会显示没有我想要的额外数据的卡片列表。我希望能够在同一个视图中显示卡片集合表 (NumberOfCopies) 中的一列,就好像它包含在第一个表中一样。如果我在 SQL Server Management Studio 中运行查询,它会通过将 cardcollections 的列附加到卡表中来返回两个表的数据。

我创建了一个视图,但无法正确通过。我收到此错误:

The model item passed into the dictionary is of type 'PagedList.PagedList`1[MTG.Models.Card]', but this dictionary requires a model item of type 'PagedList.IPagedList`1[MTG.Models.ViewCardCollectionView]'.

我了解由于我设置 CardList 变量的方式,我没有传递 ViewCardCollectionView。在使用正确的 ViewModel 时,我不知道如何执行我想要的查询。

@model IPagedList<MTG.Models.ViewCardCollectionView>

@foreach (var card in Model) {
    <tr>
         <td>
            @Html.ActionLink("Edit", "Edit", new { id=card.Cards.CardID }) |
            @Html.ActionLink("Details", "Details", new { id=card.Cards.CardID }) |
            @Html.ActionLink("Delete", "Delete", new { id=card.Cards.CardID }) |
             @Html.DisplayFor(modelItem => card.CardCollections.NumberofCopies)
        </td>
        <td>
            <b>@Html.DisplayFor(modelItem => card.Cards.Title)</b><br />
            @Html.DisplayFor(modelItem => card.Cards.MainType.Title) - @Html.DisplayFor(modelItem => card.Cards.SubType.Title)  @Html.DisplayFor(modelItem => card.Cards.AdditionalType)<br /> 
AND SO ON...

我的 ViewModel 是:

public class ViewCardCollectionView
    {
        public Card Cards { get; set; }
        public CardCollection CardCollections { get; set; }

我已经尝试了很多关于在控制器中查询的变体,并试图在返回 View() 中返回视图模型,但无济于事。任何建议将不胜感激。 :)

【问题讨论】:

    标签: sql asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    老实说,处理此问题的最简单方法是熟悉 Entity Framework 并开始使用它。您不仅编写了许多不必要的多余代码,而且通过基于用户输入手动构建 SQL 语句(我不确定 v.CollectionID 来自但我会假设应用程序的某个地方存在安全漏洞,即使它不在那里)。

    【讨论】:

      【解决方案2】:

      我可以通过将控制器更改为以下内容来使其工作:

       var viewModel = from c in db.Cards
                                      join j in db.CardCollections on c.CardID equals j.CardID
                                      where (j.IsOwned == true) && (j.CollectionID == v.CollectionID)
                                      select new ViewCardCollectionView { Cards = c, CardCollections = j };
                      return View(viewModel); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-16
        • 1970-01-01
        • 1970-01-01
        • 2014-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多