FormMethod.Get和查询字符串参数

时间:2010-05-28 03:25:04

标签: c# asp.net asp.net-mvc

我正在asp.net mvc的网站上工作。我必须显示一个视图,用户将一些搜索值(如标签和标题)添加到搜索中。我想使用相同的Index方法。我有 使我的表单使用formMethod.Get将参数作为查询字符串发送。

所以这是方法

    [HttpGet]
    public ActionResult Index(string title, string tags, int? page)
    {
        if (string.IsNullOrEmpty(title)
           return View(null);

        var list = GetSomeData();

         return View(list);

    } 

这是我的观点

<div id="searchBox">
                <% using (Html.BeginForm(null, null, FormMethod.Get))
                   { %>
                <table>
                    <tr>
                        <td>
                            <input type="hidden" id="isPosted" name="isPosted" value="1" />
                                I am looking for
                                <%=Html.TextBox("Title")%>
                                Tags:
                                <%=Html.TextBox("Tags")%>
                                <input id="search" type="submit" value="Search" />
                            </td>
                    </tr>
                </table>
                <% } %>

因此,当用户首次访问该页面时,他只会看到两个文本框和一个按钮。但是当他在标题和标签中键入内容并单击搜索按钮时,我将加载包含一些数据的视图。

现在问题是当我在标题和标签框中键入内容并单击搜索时,它们会在方法中收到,但在网址中不可见。有什么我做错了。

帮助将不胜感激。

此致

成员Parminder

3 个答案:

答案 0 :(得分:2)

我建议你拆分两个控制器动作:

public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(string title, string tags, int? page)
{
    var list = GetSomeData(title, tags, page);
    return View(list);
}

在这种情况下,您绝对不再需要表单中的隐藏字段:

<% using (Html.BeginForm()) { %>
    I am looking for
    <%= Html.TextBox("Title") %>

    Tags:
    <%= Html.TextBox("Tags") %>

    <input id="search" type="submit" value="Search" />
<% } %>

答案 1 :(得分:0)

对于您的具体问题,这不是一个严格的答案,更多的是关于我会做什么的建议。

对于这种类型的功能,我将使用jQuery对输入的数据进行部分回发。然后我将部分视图返回到视图并渲染它。

听起来很复杂,但事实并非如此。这给你带来的是一个流畅的搜索功能,整个页面永远不会发布,所以它看起来更光滑。

执行帖子的jQuery看起来像这样;

$.post("/articles/getFilteredTagList", { filter: tagString }, function(newHTML) {
  document.getElementById("tagList").innerHTML = newHTML;
});

newHTML将包含代表局部视图的渲染html。

在你的控制器中你有类似的东西;

public ActionResult getFilteredTagList(string filter)
{
  return PartialView("TagList",new Repository.KeywordsRepository().All().OrderBy(k => k.keyword1));
}

在上面的代码中,您基本上是在指示mvc渲染局部视图并返回html。这个html再次返回到你的视图,然后你可以用新的html替换div的内部。

您的局部视图可能包含其他控件,这些控件现在在已加载数据的情况下可见。

答案 2 :(得分:0)

我不明白“现在问题是当我在标题和标签框中键入内容并点击搜索时,它们会在方法中收到,但在网址中不可见。”

使用POST或GET发送数据。你已经指定了GET,我没有看到任何重定向或AJAX调用,所以我不确定你为什么不在URL中看到它。

-

请尝试以下链接中的示例代码。希望这会有所帮助。

http://weblogs.asp.net/rajbk/archive/2010/05/08/asp-net-mvc-paging-sorting-filtering-using-the-mvccontrib-grid-and-pager.aspx

相关问题