問題: 我有SubCategories類別列表,所以當我點擊SubCategory項目時,它將我重定向到條目列表。有創建ActionLink的列表。所以問題是當我爲Create ActionLink單擊SubCategoryItem時傳遞SubCategoryId。如果沒有CreateActionLink它列出的條目,但有了它,它給在索引視圖中的錯誤:如何將Id從一個視圖傳遞給另一個MVC4
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:
我明白,我路過空引用,問題是如何避免這種情況? 這裏是我的代碼:
控制器:
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)
}
我剛剛讀了兩遍你的問題,完全不知道你在做什麼。請重申。 – im1dermike 2014-10-27 20:00:29
在Create()中,爲什麼你要捕獲一個'Exception'但不處理它? null ref異常拋出在哪裏?具體來說,什麼是空? – mxmissile 2014-10-27 20:02:26
它看起來像EntryList應推高SUbcategoryID,但它不是因爲它不是模型的一部分。必須使用條目列表創建模型類,或者在ViewData/ViewBag中推入SubdcategoryID。 – 2014-10-27 20:10:30