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

MVC中同一页面调用Action时如何避免URL重复问题

问题解决:避免搜索URL重复拼接及刷新后正常搜索

问题原因

你遇到的URL重复问题是因为使用了相对路径Content/Search/。当页面处于/Content/Search/lorem时,浏览器会将相对路径拼接到当前页面路径之后,导致生成/Content/Search/Content/Search/[新关键词]的错误URL。

解决方案

1. 改用绝对路径

将跳转路径改为以/开头的绝对路径,确保每次都从网站根目录开始构建URL:

function redirectOnClick() {
  const searchValue = $(searchboxID).val().trim();
  // 开头加斜杠,使用绝对路径
  document.location = '/Content/Search/' + searchValue;
}

2. 清理冗余的事件绑定

你同时在按钮的onclick属性和JS代码里绑定了redirectOnClick函数,会导致点击时触发两次跳转,建议移除按钮标签里的onclick='redirectOnClick()':

<input type="button" value=">" class="tfbutton2" id="srcButton">

3. 修正变量定义顺序

searchboxID变量在redirectOnClick函数之后定义,可能导致函数无法正确获取该变量,调整定义顺序:

$(document).ready(function() {
  var searchboxID = "#txtSearch";
  function redirectOnClick() {
    const searchValue = $(searchboxID).val().trim();
    document.location = '/Content/Search/' + searchValue;
  }
  document.getElementById('srcButton').addEventListener("click", redirectOnClick);
});

4. 实现刷新后搜索框保留关键词

如果需要刷新ResultView页面时,搜索框自动填充当前的搜索关键词,可以从URL中提取关键词并赋值给输入框:

$(document).ready(function() {
  var searchboxID = "#txtSearch";
  // 从URL提取搜索关键词
  const pathSegments = window.location.pathname.split('/');
  if (pathSegments.length >= 3 && pathSegments[1] === 'Content' && pathSegments[2] === 'Search') {
    const searchKey = pathSegments[3] || '';
    $(searchboxID).val(decodeURIComponent(searchKey));
  }

  function redirectOnClick() {
    const searchValue = $(searchboxID).val().trim();
    if (searchValue) { // 可选:空关键词时不跳转
      document.location = '/Content/Search/' + encodeURIComponent(searchValue);
    }
  }
  document.getElementById('srcButton').addEventListener("click", redirectOnClick);
});

这里用encodeURIComponent和decodeURIComponent处理包含特殊字符的关键词,避免URL解析错误。

最终完整代码

<input type="text" id="txtSearch" class="tftextinput2" name="searchKey" size="21" maxlength="120" value="">
<input type="button" value=">" class="tfbutton2" id="srcButton">

<script type="text/javascript">
$(document).ready(function() {
  var searchboxID = "#txtSearch";
  
  // 刷新页面时填充搜索关键词
  const pathSegments = window.location.pathname.split('/');
  if (pathSegments.length >= 3 && pathSegments[1] === 'Content' && pathSegments[2] === 'Search') {
    const searchKey = pathSegments[3] || '';
    $(searchboxID).val(decodeURIComponent(searchKey));
  }

  function redirectOnClick() {
    const searchValue = $(searchboxID).val().trim();
    if (searchValue) {
      document.location = '/Content/Search/' + encodeURIComponent(searchValue);
    }
  }
  document.getElementById('srcButton').addEventListener("click", redirectOnClick);
});
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:25:46