问题: 我有SubCategories类别列表,所以当我点击SubCategory项目时,它会将我重定向到条目列表。它在列表中有Create ActionLink。因此,当我单击SubCategoryItem创建ActionLink时,问题是传递SubCategoryId。如果没有CreateActionLink,它会列出条目,但是使用它,它会在索引视图中显示错误:
Object reference not set to an instance of an object.
Line 6:
Line 7: <p>
Line 8: @Html.ActionLink("Create New", "Create", new { subCategoryId = @Model.SubCategoryId})
Line 9: </p>
Line 10:
我明白我正在传递null引用,问题是如何避免这种情况? 这是我的代码:
控制器:
public class EntryController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult EntryList(int subCategoryId)
{
var entries = EntryDAL.GetEntries(subCategoryId);
return View("_EntryList",entries);
}
public ActionResult Create(int subCategoryId)
{
var model = new Entry();
model.SubCategoryId = subCategoryId;
return View(model);
}
[HttpPost]
public ActionResult Create(Entry entry)
{
try
{
if (ModelState.IsValid)
{
var add = EntryDAL.Add(entry);
return RedirectToAction("Index");
}
return View(entry);
}
catch (Exception)
{
return View();
}
}
}
IndexView:
@model PasswordCloud.Domain.Models.SubCategory
@{
ViewBag.Title = "Index";
}
<p>
@Html.ActionLink("Create New", "Create", new { subCategoryId = @Model.SubCategoryId })
</p>
@{Html.RenderPartial("_EntryList",Model.EntryList);}
PartialView:
@model IEnumerable<PasswordCloud.Domain.Models.Entry>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Username)
</th>
<th>
@Html.DisplayNameFor(model => model.Password)
</th>
<th>
@Html.DisplayNameFor(model => model.Url)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th>
@Html.DisplayNameFor(model => model.SubCategoryId)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Username)
</td>
<td>
@Html.DisplayFor(modelItem => item.Password)
</td>
<td>
@Html.DisplayFor(modelItem => item.Url)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.SubCategoryId)
</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>
}
</table>
SubCategoryListItem查看:
@model IEnumerable<PasswordCloud.Domain.Models.SubCategory>
@foreach (var item in Model) {
@Html.ActionLink(item.Name,"Index","Entry", new { subCategoryId = item.SubCategoryId }, null)
}
答案 0 :(得分:2)
在“索引”操作中,您永远不会创建模型并将其传递给视图。因此,当它到达您使用new { subCategoryId = @Model.SubCategoryId}
的操作链接的行时,您的模型为空。因此,您将获得null ref异常。要修复它,你需要做这样的事情。
public ActionResult Index()
{
var model = ...
return View(model);
}