简体   繁体   中英

Get data from the database using mvc with foreach

I am trying to retrieve data from the database and write the records out, but i am getting an error:

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.

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

}

Controller ItemController.cs

public class ItemController : Controller
{

    private PastaContext db = new PastaContext();


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

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

}

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>

I am getting this error in this line @foreach (var item in Model) {

Edit: Added DbContext

This is happening because you are not injecting anything in your view from controller from where you are returning view.

and your view expecting IEnumerable<Oblig1.Models.Item> from your controller but as you are not passing model from controller the view gets null in Model .

try below code :-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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