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

在ASP.NET Core MVC视图中通过查询字符串传递表单隐藏输入值

解决方法

首先纠正你代码里的两个问题:

  • 隐藏输入框缺少name属性,且密码框错误使用了name="access_token",会导致参数绑定混乱
  • POST表单默认将数据放在请求体,要把access_token放到查询字符串,可通过以下两种方式实现:

方法一:利用ASP.NET Core路由助手直接拼接查询参数(推荐)

不需要隐藏输入框,直接通过asp-route-*标签助手将access_token附加到表单的action URL中:

<form asp-action="UpdatePassword" asp-controller="Account" 
      asp-route-access_token="@ViewData["AccessToken"]"
      method="post" autocomplete="on" name="login">
    <fieldset>
        <div class="field">
            <input type="password" placeholder="New password" 
                   asp-for="Password" autocomplete="new-password" />
            <span asp-validation-for="Password" class="text-danger"></span>
        </div>
    </fieldset>

    <button type="submit">Reset password</button>
</form>

asp-route-access_token会自动将access_token作为查询参数生成到表单的action地址中,提交请求时参数会出现在URL的查询字符串里。

方法二:通过JavaScript在提交时修改表单URL

如果必须保留隐藏输入框,可通过JS在表单提交前将access_token拼接到action的查询字符串:

<form asp-action="UpdatePassword" asp-controller="Account" 
      method="post" autocomplete="on" name="login" id="resetPasswordForm">
    <fieldset>
        <input type="hidden" id="accessToken" value="@ViewData["AccessToken"]" />
        <div class="field">
            <input type="password" placeholder="New password" 
                   asp-for="Password" autocomplete="new-password" />
            <span asp-validation-for="Password" class="text-danger"></span>
        </div>
    </fieldset>

    <button type="submit">Reset password</button>
</form>

<script>
document.getElementById('resetPasswordForm').addEventListener('submit', function(e) {
    const token = document.getElementById('accessToken').value;
    // 处理URL拼接逻辑,避免重复添加?
    const separator = this.action.includes('?') ? '&' : '?';
    this.action += `${separator}access_token=${encodeURIComponent(token)}`;
});
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 23:05:58