我已经能够根据控制器中的以下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));如果我只引用纸牌模型,它就会显示出卡列表,而没有我想要的额外数据。我希望能够在同一视图中显示卡片收集表(NumberOfCopies)中的一列,就像它包含在第一个表中一样。如果我在中运行该查询,它会将两个表的值都添加到cards表中。
我提出了一个观点,但不能使它正确通过。我知道这个错误:
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]'.我知道我没有传递ViewCardCollectionView,因为我有CardList变量集的方式。我不知道如何在使用正确的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; }我尝试过许多关于在控制器中查询和试图将视图模型带回返回视图()的变体,但都没有效果。如有任何建议,将不胜感激。:)
发布于 2015-08-10 20:03:16
通过将控制器更改为以下内容,我能够使它工作起来:
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); 发布于 2015-08-10 17:24:45
老实说,处理这个问题的最简单方法是熟悉实体框架并开始使用它。您不仅编写了大量不必要的多余代码,而且通过基于用户输入手动构建SQL语句(我不确定v.CollectionID来自何处,但我假设应用程序中的某个地方存在安全漏洞,即使它不在那里)来打开您的应用程序以应对SQL注入攻击。
https://stackoverflow.com/questions/31925387
复制相似问题