![](/img/trans.png)
[英]How do I carry an Id from one view to another, in ASP.NET MVC4?
[英]How to pass Id from One View to Another MVC4
問題:我具有帶有SubCategories的類別列表,所以當我單擊SubCategory項目時,它將我重定向到條目列表。 在列表的旁邊,它具有創建ActionLink。 因此,當我單擊“創建動作鏈接”的SubCategoryItem時,問題是傳遞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)
}
在索引操作中,您永遠不會創建模型並將其傳遞給視圖。 因此,當到達使用new { subCategoryId = @Model.SubCategoryId}
的操作鏈接所在的new { subCategoryId = @Model.SubCategoryId}
模型為null。 因此,您將獲得null ref異常。 要修復它,您需要執行以下操作。
public ActionResult Index()
{
var model = ...
return View(model);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.