[英]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 数据库模型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 控制器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 查看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) {
我在此行
@foreach (var item in Model) {
Edit: Added DbContext 编辑:添加了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
. 并且您的视图期望从控制器获取
IEnumerable<Oblig1.Models.Item>
,但是由于您没有从控制器传递模型,因此该视图在Model
null。
try below code :- 尝试下面的代码:-
public ActionResult Index()
{
var model = db.Items.ToList(); ////Your model that you want to pass
return View(model);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.