You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# MVC中JS函数跳转详情视图失效,如何实现正确跳转?

解决C# MVC中JS跳转详情页无法传递id的问题

你当前的JS跳转函数错误在于,服务器端执行@Url.Action('Details', 'ExpiationOffences', new { id = '__id__'})会生成类似/ExpiationOffences/Details?id=__id__的地址,之后直接拼接id会变成/ExpiationOffences/Details?id=__id__xxx,这不符合参数传递的预期,导致最终跳转地址丢失有效id。

以下是几种可行的修改方案:

方案1:替换URL中的占位符

修改JS函数,将生成的URL里的__id__占位符替换为实际传入的id参数:

function foo(id) {
    var baseUrl = "@Url.Action('Details', 'ExpiationOffences', new { id = '__id__'})";
    window.location = baseUrl.replace('__id__', id);
}

方案2:直接构造正确的URL

如果你的路由配置是默认的{controller}/{action}/{id}规则,可以直接拼接路径:

function foo(id) {
    window.location = `/ExpiationOffences/Details/${id}`;
}

如果需要适配更多路由场景,用查询字符串传递参数:

function foo(id) {
    window.location = `/ExpiationOffences/Details?id=${id}`;
}

方案3:复用视图中已有的正确URL生成逻辑

如果是给按钮绑定JS事件触发跳转,可以在按钮上预先存储正确的跳转地址:
在视图中给按钮添加data-url属性:

<button onclick="foo(this)" data-url="@Url.Action('Details', 'ExpiationOffences', new { id = item.ExpiationOffenceCode })" class="btn btn-outline-warning d-flex justify-content-center">View Detail</button>

然后修改JS函数:

function foo(btn) {
    window.location = btn.getAttribute('data-url');
}

内容的提问来源于stack exchange,提问作者user20010271

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:15:52