【问题标题】:Get data from the database using mvc with foreach使用带有foreach的mvc从数据库中获取数据
【发布时间】:2014-12-03 01:39:02
【问题描述】:

我正在尝试从数据库中检索数据并写出记录,但出现错误:

An exception of type 'System.NullReferenceException' occurred in App_Web_uaarpxja.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

数据库模型PastaModel.cs

public class Item
{
    [Key]
    public int Itemid { get; set; }
    public string Itemname { get; set; }
    public int Itemprice { get; set; }
    public int Currentstock { get; set; }
    public string Itemtype { get; set; }
    public string pictureURL { get; set; }
}

public class PastaContext : DbContext
{

    public PastaContext()
        : base("name=PastaModel")
    {
        Database.CreateIfNotExists();
    }

    public DbSet<Item> Items { get; set; }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }

}

控制器 ItemController.cs

public class ItemController : Controller
{

    private PastaContext db = new PastaContext();


    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index()
    {
        return View();
    }

}

查看Index.cshtml

@model IEnumerable<Oblig1.Models.Item>

<!DOCTYPE html>

<br />
<br />

<html>
<head>
    <title>Index</title>
</head>
<body>


@foreach (var item in Model)
{

     <p>@item.Itemname</p>

}


</body>
</html>

我在@foreach (var item in Model) {这一行收到此错误

编辑:添加 DbContext

【问题讨论】:

    标签: c# asp.net-mvc web-applications model-view-controller foreach


    【解决方案1】:

    发生这种情况是因为您没有从返回视图的控制器向视图中注入任何内容。

    您的视图期望来自控制器的IEnumerable&lt;Oblig1.Models.Item&gt;,但由于您没有从控制器传递模型,因此视图在Model 中变为空。

    试试下面的代码:-

    public ActionResult Index()
        {
            var model = db.Items.ToList(); ////Your model that you want to pass
            return View(model);
        }
    

    【讨论】:

    • 然后我得到了,The model item passed into the dictionary is of type 'System.Data.Entity.DbSet1[Oblig1.Models.Item]',但是当我尝试时,这本字典需要一个类型为“Oblig1.Models.Item”的模型项。跨度>
    • 新错误...The model item passed into the dictionary is of type 'System.Collections.Generic.List``1[Oblig1.Models.Item]', but this dictionary requires a model item of type 'Oblig1.Models.Item'@Neel
    • 你的观点有没有改变? @mv700 你的观点期待 ienumerable
    • 这是您视图的第一行“@model IEnumerable”吗? @mv700
    • 是的,@model IEnumerable&lt;Oblig1.Models.Item&gt;@Neel
    猜你喜欢
    • 2014-04-10
    • 2012-06-13
    • 2011-10-19
    • 2015-07-10
    • 2014-10-16
    • 2017-05-04
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多