繁体   English   中英

使用MVC和实体框架查看数据库中的数据

[英]View data from database using MVC & Entity Framework

我正在尝试查看数据库中的项目列表(我正在使用Entity Framework)。

我的存储库方法:

public List<string> getListOfItems(int i)
{
    return (from x in db.Items where x.ID == i select x.Text).ToList();
}

我的控制器:

public ActionResult Index()
{
    var itemOutput = repo.getListOfItems(1); // I just put 1 since I didn't know how to specify "i" - However theoretically it should return first item in database but its not
    ViewBag.itemOutput = itemOutput ;

    return View();
}

模型:

public class items
{
    [Key]
    public int ID{ get; set; }
    public string name{ get; set; }
    public string quantity{ get; set; }
}

ItemModel:

public class itemModels
{ 
    public List<List<string>> itemData{ get; set; }
}

视图:

@foreach (var item in ViewBag.itemOutput )
{
    <table id="t01">
        <tr>
            <td>@item.name</td>
        </tr>
    </table>
}

回答:

ViewBag.itemOutput是一个List<string> ,它使item成为string

因此,在视图中使用@item而不是@item.name (因为string没有.name属性):

@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();
}

然后只需调用不带参数的getListOfItems()


随机评论:

1)不要使用复数作为类名, 除非该类有点东西的集合

--> public class item // without s

2)您在评论中说items是完整的varchar ,根据您的类定义(您具有IDnamequantity ),这是不正确的。

3)使用string作为quantity有点奇怪。

4)您确实可以将getListOfItems方法更改为:

public List<item> getListOfItems()
{
    return (from x in db.Items select x).ToList();
    // which can be simplified to:
    // return db.Items.ToList();
}

但是您应该将视图更改回@item.name

但是,这将允许您执行以下操作:

@foreach (var item in ViewBag.itemOutput )
{
    <table id="t01">
        <tr>
            <td>@item.name</td>
            <td>@item.quantity</td>
        </tr>
    </table>
}

5)您有一个ItemModel但没有使用它。 您可以修改它并使用它来代替ViewBag

getListOfItems()返回字符串列表,但是您引用的是ViewBag.itemOutput中的实际对象

代替select x.Text,请选择select x,并使返回值List<items>

public List<items> getListOfItems(int i)
{
    return (from x in db.Items where x.ID == i select x).ToList();
}

然后,您可以将剃刀模板保持不变以引用@ item.name

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM