MVC3:HTML.BeginForm搜索返回空查询字符串

3
在MVC3应用程序中,我有以下视图:
@using (Html.BeginForm("Index", "Search", new {query = @Request.QueryString["query"]}, FormMethod.Post))
{
   <input type="search" name="query" id="query" value="" />
}

当我在浏览器中输入网址“/Search?query=test”时,我的Index操作中的Request.Querystring完美地读出了搜索值(我已将路由设置为忽略URL中的Action)。但是当我在搜索框中输入时,它命中了正确的操作和控制器(因此路由似乎没有问题),但查询字符串仍然为空。我做错了什么?
1个回答

4

问题在于你正在查找 Request.QueryString 集合。但你正在进行一个 POST 请求,所以 query 值在 Request.Form 集合中。但是我认为你想要将文本框填充到数据中,可以像我的样例那样做。

样例

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
   <input type="search" name="query" id="query" value="@Request.Form["query"]" />
}

但这并不是真正的MVC方法。您需要为此创建一个视图模型(ViewModel)。

模型(Model)

namespace MyNameSpace.Models
{
    public class SearchViewModel
    {
        public string Query { get; set; }
    }
}

视图

@model MyNameSpace.Models.SearchViewModel

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
   @Html.TextBoxFor(x => x.Query)
   <input type="submit" />
}

控制器

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

[HttpPost]
public ActionResult Index(SearchViewModel model)
{
    // do your search
    return View(model);
}

嗨,dknaack,感谢您的快速回复。我担心改变参数顺序不会有任何影响。 - stefjnl
嗨,dknaack,那就行了!它在Request.Form中。谢谢!你说的ViewModel是什么意思? - stefjnl
@jim 是的,但 ViewModel 解决方案才是真正的答案。 - dknaack
dknaack,感谢您的详细回复。我会去实现您的真正MVC示例 :) - stefjnl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接