ASP.NET MVC中点击View表格链接向Action传递对应元素ID及解决空指针异常问题
解决ASP.NET MVC表格链接传递ID及空指针异常问题
首先,咱们先理清问题根源:你点击Remove/Edit链接时出现的空指针异常,本质是因为没有把对应行的记录ID传递给后台Action,导致Action在处理时找不到对应的实体,进而触发空引用错误。
要实现点击Remove链接传递对应元素ID,你只需要在生成链接时,把当前行模型的ID作为参数传给Url.Action方法即可,同时咱们可以优化一下for循环的写法,让代码更简洁高效:
修改后的View代码
@model List<MyMainModel> @using System.Collections; @using System.Web; @{ ViewData["Title"] = "Display"; } <h1>Display</h1> <table border="1" cellpadding="20" style="table-layout:fixed"> <tr> <th> UserName </th> <th> Password </th> <!-- 修正了表头的拼写错误 --> <th> Email </th> <th colspan="2"> Options </th> </tr> @for (int i = 0; i < Model.Count; i++) { var currentItem = Model[i]; // 缓存当前项,避免重复索引访问 <tr> <td> @currentItem.USERNAME </td> <td> @currentItem.PASSWORD </td> <td> @currentItem.EMAIL </td> <td> <!-- 传递当前项的ID到RemoveRow Action --> <a href="@Url.Action("RemoveRow", "MyMain", new { id = currentItem.ID })">Remove</a> </td> <td> <!-- 同理,Edit链接也传递对应ID --> <a href="@Url.Action("EditRow", "MyMain", new { id = currentItem.ID })">Edit</a> </td> </tr> } </table>
关键修改点说明
- 传递ID参数:在
Url.Action的第三个参数中,通过匿名对象new { id = currentItem.ID }把当前行的ID传递给后台Action。这里假设你的MyMainModel类有一个名为ID的属性(如果是其他名称,比如UserId,替换成对应的字段名即可)。 - 优化循环写法:用
Model[i]直接访问列表元素(比ElementAt(i)更高效,因为List原生支持索引访问),并且缓存到currentItem变量中,让代码更清晰易读。 - 顺便修正了表头里的拼写错误
PAssword为Password(可选,但更符合编码规范)。
后台Action的接收示例
你的MyMainController里的RemoveRow Action需要接收这个ID参数,示例如下:
public ActionResult RemoveRow(int id) { // 根据ID找到对应的记录并执行删除逻辑 var itemToRemove = _dbContext.MyMainModels.FirstOrDefault(m => m.ID == id); if (itemToRemove != null) { _dbContext.MyMainModels.Remove(itemToRemove); _dbContext.SaveChanges(); } return RedirectToAction("Display"); // 删除后跳回展示页面 }
这样修改后,点击Remove链接时就会把对应行的ID传递给后台Action,Action可以根据ID准确找到要删除的记录,也就不会出现空指针异常了。
内容的提问来源于stack exchange,提问作者Adarsh s
相关产品推荐
相关产品推荐

