Asp.net mvc 正在查询数据库但返回null
我试图将数据库中的项目列表到视图中,但返回空值 我知道连接一定在一定程度上起作用,因为在我的数据库中表不存在,但一旦我运行了我的程序,它就创建了表。但是,当我将内容添加到表中时,视图仍然返回NULL 此外,我还没有接触到审查表,只是担心让餐厅工作 餐厅 Index.cshtmlAsp.net mvc 正在查询数据库但返回null,asp.net-mvc,asp.net-mvc-5,Asp.net Mvc,Asp.net Mvc 5,我试图将数据库中的项目列表到视图中,但返回空值 我知道连接一定在一定程度上起作用,因为在我的数据库中表不存在,但一旦我运行了我的程序,它就创建了表。但是,当我将内容添加到表中时,视图仍然返回NULL 此外,我还没有接触到审查表,只是担心让餐厅工作 餐厅 Index.cshtml @model IEnumerable @{ ViewBag.Title=“主页”; } @{ 如果(型号!=null) { foreach(模型中的var项目) { @项目名称 @item.City,@item.Cou
@model IEnumerable
@{
ViewBag.Title=“主页”;
}
@{
如果(型号!=null)
{
foreach(模型中的var项目)
{
@项目名称
@item.City,@item.Country
}
}
其他的
{
无效的
}
}
您需要将模型传递回视图
OdeToFoodDb _db = new OdeToFoodDb();
public ActionResult Index()
{
var model = _db.Restaurants.ToList();
return View(model);
}
您需要将模型传递回视图
OdeToFoodDb _db = new OdeToFoodDb();
public ActionResult Index()
{
var model = _db.Restaurants.ToList();
return View(model);
}
实际上,您从未将模型发送到视图。将其作为参数传递:
OdeToFoodDb _db = new OdeToFoodDb();
public ActionResult Index()
{
var model = _db.Restaurants.ToList();
return View(model);
}
此外,通常最好不要在共享范围内创建数据库上下文。让上下文尽可能靠近使用它的地方,并且只在您真正需要的时候扩展它的范围。大概是这样的:
public ActionResult Index()
{
using (var _db = new OdeToFoodDb())
{
var model = _db.Restaurants.ToList();
return View(model);
}
}
共享作用域中的数据库上下文/连接只是在问问题,除非您密切注意自己在做什么。随着代码变得越来越复杂,其他方法很可能会尝试使用它,并且此时它可能处于未知状态。您从未实际将模型发送到视图。将其作为参数传递:
OdeToFoodDb _db = new OdeToFoodDb();
public ActionResult Index()
{
var model = _db.Restaurants.ToList();
return View(model);
}
此外,通常最好不要在共享范围内创建数据库上下文。让上下文尽可能靠近使用它的地方,并且只在您真正需要的时候扩展它的范围。大概是这样的:
public ActionResult Index()
{
using (var _db = new OdeToFoodDb())
{
var model = _db.Restaurants.ToList();
return View(model);
}
}
共享作用域中的数据库上下文/连接只是在问问题,除非您密切注意自己在做什么。随着代码变得越来越复杂,其他方法很可能会尝试使用它,而此时它可能处于未知状态
public ActionResult Index()
{
using (var _db = new OdeToFoodDb())
{
var model = _db.Restaurants.ToList();
return View(model);
}
}