使用提交时的文本框值作为查询字符串变量

Nul*_*nce 0 asp.net asp.net-mvc

如何获取文本框值并在提交时在查询字符串中使用它?我希望它从这开始,

/新闻?最爱=真

在用户进入搜索并点击搜索后,最终会出现类似内容.

/新闻?查询=测试与收藏=真

控制器动作看起来像这样

public ActionResult Index(string query,bool favorites)
{
   //search code   
}
Run Code Online (Sandbox Code Playgroud)

这个问题与我想做的事情很接近,但是我想使用查询字符串并维护查询字符串中的现有值.

谢谢.

Dar*_*rov 5

两种可能性:

  1. 将文本框放在<form>with中method="GET"
  2. 使用javascript读取值并将其传递给服务器(使用AJAX或window.location执行重定向)

示例<form>:

<% using (Html.BeginForm("index", "news", FormMethod.Get)) { %>
    <label for="query">Query:</label>
    <%= Html.TextBox("query") %>
    <input type="submit" value="Search" />
<% } %>
Run Code Online (Sandbox Code Playgroud)

使用javascript的示例:

<label for="query">Query:</label>
<%= Html.TextBox("query") %>
<%= Html.ActionLink("Search", "index", "news", new { id = "search" }) %>
Run Code Online (Sandbox Code Playgroud)

然后在一个单独的js文件中:

$(function() {
    $('#search').click(function() {
        var query = $('#query').val();
        // Here you could use AJAX instead of window.location if you wish
        window.location = this.href + '?query=' + encodeURIComponent(query);
        return false;
    });
});
Run Code Online (Sandbox Code Playgroud)