如何解决Ajax.ActionLink动态生成时'item不存在于当前上下文'的错误?
我来帮你解决这个@Ajax.ActionLink的参数问题,顺便给你几个可行的替代方案~
一、修复@Ajax.ActionLink的"item不存在"错误
首先,这个错误大概率是参数顺序错误或者Razor语法解析问题导致的,我们先给出正确的写法,再分析原因:
1. 正确的@Ajax.ActionLink用法(循环内)
@foreach (var item in Model) { <tr> <td>@item.Deal_Date</td> <td>@item.Total_Amount_Remaining</td> <td>@item.Dealer_Name</td> <td>@item.Validity_Date</td> <td>@item.Location</td> <td>@item.Deal_Amount</td> <td>@item.Client_Info.Client_Name</td> <td> @Ajax.ActionLink( "Receive payment", "RecievePayment", new { id = item.Deal_ID }, // 路由参数,这里能正确访问循环变量item new AjaxOptions { HttpMethod = "GET", OnSuccess = "handlePaymentSuccess" // 你的成功回调函数名 } ) </td> </tr> }
2. 必要的依赖脚本
Ajax.ActionLink依赖微软的不显眼Ajax脚本,必须在视图/布局页中引入:
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
错误原因分析
你遇到的"item不存在"提示,最常见的场景是:
- 参数顺序搞反了:
Ajax.ActionLink的第三个参数是路由值(routeValues),第四个是AjaxOptions。如果把这两个参数颠倒,item.Deal_ID会被放到AjaxOptions的上下文里,而这里无法访问循环变量item,就会触发错误。 - Razor语法嵌套错误:如果代码里有未闭合的标签/括号,会导致Razor解析器错误判断
item的作用域。
二、更灵活的替代方案:手动写jQuery Ajax请求
很多开发者会放弃Ajax.ActionLink,转而用手动jQuery Ajax来获得更自由的控制,还能彻底避免Razor作用域问题:
1. 修改视图,用普通按钮替代ActionLink
@foreach (var item in Model) { <tr> <!-- 其他列保持不变 --> <td> <button class="btn-receive-payment" data-dealid="@item.Deal_ID">Receive payment</button> </td> </tr> }
2. 添加Ajax处理脚本
<script> $(function() { // 绑定按钮点击事件 $('.btn-receive-payment').click(function() { const dealId = $(this).data('dealid'); $.ajax({ url: '@Url.Action("RecievePayment")', type: 'GET', data: { id: dealId }, success: function(response) { // 这里写你的成功回调逻辑,比如动态生成表格行 const newRow = `<tr> <td>${response.Deal_Date}</td> <td>${response.Total_Amount_Remaining}</td> <td>${response.Dealer_Name}</td> <!-- 其他列根据返回数据拼接 --> </tr>`; // 把新行插入到目标表格(比如id为paymentTable的表格) $('#paymentTable').append(newRow); }, error: function() { alert('请求失败,请稍后重试'); } }); }); }); </script>
这种方式的优势:
- 完全控制请求的每个环节(请求方式、参数、错误处理等)
- 彻底避免Razor语法的作用域问题
- 回调逻辑更灵活
三、控制器代码的小优化
另外注意你的控制器方法里,decimal是值类型,不能为null,所以id == null的判断无效,建议改成可空值类型:
public ActionResult RecievePayment(decimal? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Sell_Deal sell_deal = db.Sell_Deal.Find(id.Value); if (sell_deal == null) { return HttpNotFound(); } ViewBag.Client_ID = new SelectList(db.Client_Info, "Client_ID", "Client_Name", sell_deal.Client_ID); return View(sell_deal); }
内容的提问来源于stack exchange,提问作者Uzair Raza
相关产品推荐
相关产品推荐

