【问题标题】:Use textbox value on submit as a query string variable在提交时使用文本框值作为查询字符串变量
【发布时间】:2011-01-12 19:34:31
【问题描述】:

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

/News?favorites=True

并在用户输入搜索并点击搜索后结束。

/News?query=test&favorites=True

控制器动作如下所示

public ActionResult Index(string query,bool favorites)
{
   //search code   
}

这个question 与我想做的很接近,但我想使用查询字符串并维护查询字符串中的现有值。

谢谢。

【问题讨论】:

    标签: asp.net asp.net-mvc


    【解决方案1】:

    两种可能:

    1. 将文本框放在<form>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" />
    <% } %>
    

    javascript 示例:

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

    然后在一个单独的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;
        });
    });
    

    【讨论】:

    • 感谢您的快速回复。使用表单标签是我一直在寻找的,但问题是它会清除所有现有的查询参数。使用此方法,如果 url 是 /News?favorites=True 并且我通过搜索提交,并且抛出异常(缺少 bool 参数),并且收藏夹丢失。有没有办法保留当前的参数?
    • 您可以将favorites 参数作为隐藏标签包含在表单中:&lt;%=Html.Hidden("favorites") %&gt;
    • 太棒了,谢谢!将 " /> 添加到表单标签中,我很好。
    • 我很高兴您包含了 encodeURIComponent,当您只是在寻找快速修复(我几乎做到了)时,这很容易被忽略。
    • 如果我想在 div 元素中显示搜索结果怎么办? @DarinDimitrov
    【解决方案2】:

    使用 Darin 的上述 &lt;form&gt; 答案但带有 Razor 标记:

    @using (Html.BeginForm("index", "news", FormMethod.Get)) 
    { 
    <label for="query">Search:</label>
        @Html.TextBox("query")
    <input type="submit" value="Search" />
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2013-08-28
      • 1970-01-01
      相关资源
      最近更新 更多