【发布时间】:2015-11-23 17:45:43
【问题描述】:
在 List 类型的视图中,我试图将视图中的项目 id(在本例中为电子邮件)传递给控制器中的 actionResult:我使用了以下代码():
@Html.ActionLink("Contact", "CreateMessage", "Member", new { id = item.eMail })
我得到一个空引用,因为传递的 id 是空的。
这是工作正常的视图,其中的 id 不为空:
@model IEnumerable<Mutuelle.Domain.Entities.Adherent>
@{
ViewBag.Title = "lister";
}
<h2>Liste des adhérents</h2>
<table class="table">
<tr>
<body style="overflow:scroll;">
<th>
@Html.DisplayNameFor(model => model.dateOfBirth)
</th>
<th>
@Html.DisplayNameFor(model => model.address)
</th>
<th>
@Html.DisplayNameFor(model => model.phoneNumber)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.dateOfBirth)
</td>
<td>
@Html.DisplayFor(modelItem => item.address)
</td>
<td>
@Html.DisplayFor(modelItem => item.phoneNumber)
</td>
<td>
@Html.ActionLink("Contacter", "CreateMessage", "MembreComite", new { id = item.eMail })
</td>
</tr>
}
</table>
这是控制器:
public ActionResult CreateMessage(string id)
{
Message message = new Message();
return View(message);
}
[HttpPost]
public ActionResult CreateMessage(Message message, string id)
{
if (ModelState.IsValid)
{
AMDMService service = new AMDMService();
Member member = service.GetMemberByeMail(id);
message.member = member;
message.adherentId = id;
member.listMessages.Add(message);
return RedirectToAction("listeMessages");
}
return View(message);
}
【问题讨论】:
-
哪里有错误?
-
这是导致空引用错误的行(无法将值 NULL 插入到adherentId列中):'message.adherentId = id;'因为从视图传递的 id 是 NULL
-
这是表单 POST 提交吗?表格的其余部分在哪里?用浏览器的网络监视器观察请求——请求体是什么样的?它与您的动作签名匹配吗?此外,
foreach在发送集合时很少一起工作。请改用for循环。见here。 -
这是整个表格。 “for”不起作用,它会导致错误,视图是使用类型自动生成的“List”被强类型化到实体“member”
-
如果您尝试执行 GET 操作,则您使用的覆盖错误:
ActionLink(linkText, action, controller, htmlAttributes)而不是ActionLink(linkText, action, controller, routeValues, htmlAttributes)。
标签: razor asp.net-mvc-5 nullreferenceexception