C# 使用MVC查看数据库中的数据&;实体框架
我试图查看数据库中的项目列表(我使用的是实体框架) 我的存储库方法:C# 使用MVC查看数据库中的数据&;实体框架,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我试图查看数据库中的项目列表(我使用的是实体框架) 我的存储库方法: public List<string> getListOfItems(int i) { return (from x in db.Items where x.ID == i select x.Text).ToList(); } 型号: public class items { [Key] public int ID{ get; set; } public string name{
public List<string> getListOfItems(int i)
{
return (from x in db.Items where x.ID == i select x.Text).ToList();
}
型号:
public class items
{
[Key]
public int ID{ get; set; }
public string name{ get; set; }
public string quantity{ get; set; }
}
项目模型:
public class itemModels
{
public List<List<string>> itemData{ get; set; }
}
公共类项目模型
{
公共列表项数据{get;set;}
}
视图:
@foreach(ViewBag.itemOutput中的变量项)
{
@item.name
}
getListOfItems()返回字符串列表,但您引用的是ViewBag.itemOutput中的实际对象
而不是选择x。文本执行选择x,并使返回值<代码>列表
public List getListOfItems(inti)
{
返回(从db.Items中的x返回,其中x.ID==i选择x.ToList();
}
然后,您可以保持剃须刀模板不变,以引用@item.name答案:
ViewBag.itemOutput
是一个列表
,它使项
成为字符串
因此,在视图中使用@item
而不是@item.name
(因为string
没有.name
属性):
@foreach (var item in ViewBag.itemOutput )
{
<table id="t01">
<tr>
<td>@item</td>
</tr>
</table>
}
2) 您在评论中说,项目
已满varchar
,根据您的类定义,这是不真实的(您有ID
,名称
,数量
)
3) 使用字符串
表示数量
有点奇怪
4) 您确实可以将getListOfItems
方法更改为:
public List<item> getListOfItems()
{
return (from x in db.Items select x).ToList();
// which can be simplified to:
// return db.Items.ToList();
}
5) 您有一个
ItemModel
,但您没有使用它。您可以修改它并使用它来代替ViewBag
问题是什么?它没有显示数据库中的项目。从技术上讲,它应该显示第一项(例如相机),您是否检查了从数据库检索的数据,是否检查了正确的数据库指向?为什么您在这里没有使用正确的模型?不要使用ViewBag
,除非您必须这样做。如果您不知道如何将模型传递到视图,那么您应该回到基础知识,首先学习一些教程。是的,1)不使用ViewBag,2)使用ViewModel,3)GetList(ID)将始终返回0或1个项目的列表。是的,我的数据库中的项目是varchar-所有字符串。那么你有什么建议呢?我想说的是,你的Razor模板试图引用一个完整的项目,但你只是从存储库返回字符串。@int21h是正确的。您的操作方法和视图不匹配。太好了!:)它起作用了,但目前在我的控制器中,我将var itemOutput=repo.getListOfItems(1);因此,它返回的第一个项是如何从db.items中的x循环遍历数据库表中的项,其中x.ID==我将返回一个ID==1的项。您要求的是一个项目,并在列表中返回。@Warda我编辑了我的答案,添加了“获取完整列表”部分完美!非常感谢!:))@我编辑了我的答案,添加了一些评论
public List<items> getListOfItems(int i)
{
return (from x in db.Items where x.ID == i select x).ToList();
}
@foreach (var item in ViewBag.itemOutput )
{
<table id="t01">
<tr>
<td>@item</td>
</tr>
</table>
}
public List<string> getListOfItems()
{
return (from x in db.Items select x.Text).ToList();
}
--> public class item // without s
public List<item> getListOfItems()
{
return (from x in db.Items select x).ToList();
// which can be simplified to:
// return db.Items.ToList();
}
@foreach (var item in ViewBag.itemOutput )
{
<table id="t01">
<tr>
<td>@item.name</td>
<td>@item.quantity</td>
</tr>
</table>
}