Asp.net Html.BeginForm在提交时丢失RouteValue

Asp.net Html.BeginForm在提交时丢失RouteValue,asp.net,asp.net-mvc,razor,forms,url-parameters,Asp.net,Asp.net Mvc,Razor,Forms,Url Parameters,我有一个显示人员列表的页面。它可以按名字和姓氏排序。要搜索人员,我有以下表单: @using (Html.BeginForm("Index", "Persons", new { sort = ViewBag.Sort }, FormMethod.Get)) { <p> Search: @Html.TextBox("search", ViewBag.Search as string) <input type="submit" value="

我有一个显示人员列表的页面。它可以按名字和姓氏排序。要搜索人员,我有以下表单:

@using (Html.BeginForm("Index", "Persons", new { sort = ViewBag.Sort }, FormMethod.Get))
{
    <p>
        Search: @Html.TextBox("search", ViewBag.Search as string)
        <input type="submit" value="Search" />
    </p>
}

正如预期的那样,操作中包括了
?sort=firstname
。但是,当我按下提交按钮(搜索)时,
sort
参数丢失。新url只有
?搜索=…
。如何解决此问题?

您需要将
sort
的值存储在表单中的某个位置,以便将其作为提交的一部分。您可以尝试隐藏输入:

@using (Html.BeginForm("Index", "Persons"))
{
    <input type="hidden" id="sort" value="firstname" />
    <p>
        Search: @Html.TextBox("search", ViewBag.Search as string)
        <input type="submit" value="Search" />
    </p>
}

当您查看输出html时,会得到如下结果:

<form action="/persons/index?sort=asc" method="get">
    <p>
        <input type="text" name="search" />
        <input type="submit" value="Search" />
    </p>
</form>


这似乎是完全合法的,您可能会期望出现类似追加post输入查询的行为。然而,这受到HTTP规范的限制。表单post操作的查询字符串不会被追加。这就是为什么查询参数不能在服务器端工作。然而,我希望Asp.net能够自动将表单的参数获取到隐藏字段中,而现在却没有

作为一种适当的解决方案,您必须将输入放入表单中,以便使用隐藏字段执行以下操作:

@using (Html.BeginForm("Index", "Persons", FormMethod.Get))
{
   @Html.Hidden("sort",ViewBag.Sort)
   <p>
      Search: @Html.TextBox("search", ViewBag.Search as string)
      <input type="submit" value="Search" />
   </p>
}
@使用(Html.BeginForm(“Index”,“Persons”,FormMethod.Get))
{
@隐藏(“排序”,ViewBag.sort)

搜索:@Html.TextBox(“搜索”,ViewBag.Search为字符串)

}
在Razor中,这似乎是最好的方法。谢谢
<form action="/persons/index?sort=asc" method="get">
    <p>
        <input type="text" name="search" />
        <input type="submit" value="Search" />
    </p>
</form>
@using (Html.BeginForm("Index", "Persons", FormMethod.Get))
{
   @Html.Hidden("sort",ViewBag.Sort)
   <p>
      Search: @Html.TextBox("search", ViewBag.Search as string)
      <input type="submit" value="Search" />
   </p>
}