我将数据从数据库绑定到webgrid,我想在webgrid的每一行中保持一个actionlink编辑,尝试下面的一行,但在下面的行附近得到Object reference not set to an instance of an object
错误,我的模型名称是User
foreach(var item in Model)
我也发布了整个代码
var grid = new WebGrid(source: MvcPopupGrid.Models.User.Users, rowsPerPage: 5);
@grid.GetHtml(
tableStyle: "grid", headerStyle: "gridhead", footerStyle: "paging", rowStyle: "td-dark", alternatingRowStyle: "td-light",
columns:
grid.Columns(
grid.Column(header: "Id", format: @<text><label id="lblId" title="@item.Id">@item.Id</label></text>),
grid.Column(header: "Name", format: @<text><label id="lblName" title="@item.Name">@item.Name</label></text>),
grid.Column(header: "College", format: @<text><label id="lblCollege" title="@item.College">@item.College</label></text>),
grid.Column(header: "PassedOut", format: @<text><label id="lblPassedOut" title="@item.PassedOut">@item.PassedOut</label></text>),
grid.Column(header: "Mobile", format: @<text><label id="lblMobile" title="@item.Mobile">@item.Mobile</label></text>)))
foreach(var item in Model)
{
@item.Id
@item.Name
@item.College
@item.PassedOut
@item.Mobile
@Html.ActionLink("Edit", "UserEdit", new { Id = "@item.Id" }, new { @class = "abookModal", title = "Edit User" })
}
答案 0 :(得分:4)
您的模型为空。我猜你的观点是强烈输入的一些集合:
@model IEnumerable<SomeType>
@foreach (var item in Model)
{
...
}
除了在呈现此视图的控制器操作内部,您没有将任何模型传递给视图,或者您传递了null。因此,请确保不会发生这种情况:
public ActionResult SomeAction()
{
IEnumerable<SomeType> model = ... fetch the collection from somewhere and make sure this collection is not null
return View(model);
}
我注意到的另一件事是您将WebGrid源指向某个MvcPopupGrid.Models.User.Users
属性:
var grid = new WebGrid(source: MvcPopupGrid.Models.User.Users, rowsPerPage: 5);
您还应该确保此属性不返回null。