Asp.net mvc 序列不包含任何元素error-MVC(模型和数据访问)
我正试着按照程序去做,但我遇到了一个我无法处理的错误。我创建了以下操作:Asp.net mvc 序列不包含任何元素error-MVC(模型和数据访问),asp.net-mvc,linq,view,error-handling,model,Asp.net Mvc,Linq,View,Error Handling,Model,我正试着按照程序去做,但我遇到了一个我无法处理的错误。我创建了以下操作: public ActionResult Browse(string category) { using (OnlineStoreDbContext db = new OnlineStoreDbContext()) { // Get category and its associated products
public ActionResult Browse(string category)
{
using (OnlineStoreDbContext db = new OnlineStoreDbContext())
{
// Get category and its associated products
var categoryModel = db.Categories.Include("Products")
.Single(c => c.Title == category);
return View(categoryModel);
}
}
然后我创建了相应的视图:
@model OnlineStoreMVC.Core.Models.Category
@{
ViewBag.Title = "Browse";
}
<h2>Browse Category: @Model.Title</h2>
<ul>
@foreach (var product in Model.Products)
{
<li>
@product.Title
</li>
}
</ul>
我已经尝试过用SingleOrDefault替换Single,但是错误是
“对象引用未设置为对象的实例。”
关于视图中的那一行:“浏览类别:@Model.Title”
问题是,您在url中将cat作为密钥传递,它应该是类别。所以你应该调用http://localhost:51642/Store/Browse?category=Action
关于错误“对象引用未设置为对象实例”,您必须将操作方法更改为:
public ActionResult Browse(string category)
{
using (OnlineStoreDbContext db = new OnlineStoreDbContext())
{
// Get category and its associated products
var categoryModel = db.Categories.Include("Products")
.SingleOrDefault(c => c.Title == category);
if (categoryModel == default(Category))
{
categoryModel = new Category();
categoryModel.Products = new List<Product>();
}
return View(categoryModel);
}
}
公共操作结果浏览(字符串类别)
{
使用(OnlineStoreDbContext db=new OnlineStoreDbContext())
{
//获取类别及其关联产品
var categoryModel=db.Categories.Include(“产品”)
.SingleOrDefault(c=>c.Title==类别);
如果(categoryModel==默认(类别))
{
categoryModel=新类别();
categoryModel.Products=新列表();
}
返回视图(类别模型);
}
}
类别的价值是什么?用debug检查一下。
public ActionResult Browse(string category)
{
using (OnlineStoreDbContext db = new OnlineStoreDbContext())
{
// Get category and its associated products
var categoryModel = db.Categories.Include("Products")
.SingleOrDefault(c => c.Title == category);
if (categoryModel == default(Category))
{
categoryModel = new Category();
categoryModel.Products = new List<Product>();
}
return View(categoryModel);
}
}