【发布时间】:2018-09-04 14:36:20
【问题描述】:
我使用Controller中的“列表视图”生成了一个storeList.cshtml文件,在这个视图文件中,有一行:
foreach (var item in Model) {}
当我运行应用程序时,此行不断收到“Nullreference”错误和“对象引用未设置为对象实例”错误。
我很困惑,因为:
1) 这个视图文件是自动生成的;那为什么不正确呢?
2)我使用了完全相同的方式(“列表视图”)并生成了许多其他视图文件,从未遇到过这个问题。
<table class="uk-table">
<tr>
<th>
@Html.DisplayNameFor(model => model.CategoryID)
</th>
<th>
@Html.DisplayNameFor(model => model.typeID)
</th>
<th>
@Html.DisplayNameFor(model => model.name)
</th>
<th>
@Html.DisplayNameFor(model => model.storeUrl)
</th>
<th>
@Html.DisplayNameFor(model => model.storedes)
</th>
<th>
@Html.DisplayNameFor(model => model.tags)
</th>
<th>
@Html.DisplayNameFor(model => model.image)
</th>
<th>
@Html.DisplayNameFor(model => model.metaTitle)
</th>
<th>
@Html.DisplayNameFor(model => model.metaDescription)
</th>
<th>
@Html.DisplayNameFor(model => model.popular)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.CategoryID)
</td>
<td>
@Html.DisplayFor(modelItem => item.typeID)
</td>
<td>
@Html.DisplayFor(modelItem => item.name)
</td>
<td>
@Html.DisplayFor(modelItem => item.storeUrl)
</td>
<td>
@Html.DisplayFor(modelItem => item.storedes)
</td>
<td>
@Html.DisplayFor(modelItem => item.tags)
</td>
<td>
@Html.DisplayFor(modelItem => item.image)
</td>
<td>
@Html.DisplayFor(modelItem => item.metaTitle)
</td>
<td>
@Html.DisplayFor(modelItem => item.metaDescription)
</td>
<td>
@Html.DisplayFor(modelItem => item.popular)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.id }) |
@Html.ActionLink("Details", "Details", new { id=item.id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.id })
</td>
</tr>
}
控制器
public ActionResult storeList()
{
return View();
}
型号
public partial class store
{
public store()
{
this.Reviews = new HashSet<Review>();
}
public int id { get; set; }
public Nullable<int> CategoryID { get; set; }
public Nullable<int> typeID { get; set; }
public string name { get; set; }
public string storeUrl { get; set; }
public string storedes { get; set; }
public string tags { get; set; }
public string image { get; set; }
public string metaTitle { get; set; }
public string metaDescription { get; set; }
public Nullable<bool> popular { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Review> Reviews { get; set; }
public virtual Type Type { get; set; }
}
错误
对象引用未设置为对象的实例。
说明:执行过程中发生未处理的异常 解决当前的网络请求。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详情:System.NullReferenceException:对象引用未设置为对象的实例。
让我知道如何解决这个问题?
谢谢
【问题讨论】:
-
我会再次编辑我的问题
-
你应该设置模型视图(yourmodel);像这样
-
问题是我在控制器中创建了我的表 obj 以检查我是否从表中获取数据并且它没有获得任何价值。
-
udara kasun view(db.mymodel.tolist());这是我必须做的,而且工作正常。谢谢队友
标签: .net asp.net-mvc-5