gpt4 book ai didi

asp.net - Html.BeginForm 在提交时丢失了routeValues

转载 作者:行者123 更新时间:2023-12-02 12:22:10 24 4
gpt4 key购买 nike

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

@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>
}

ViewBag.SearchViewBag.Sort 包含上次使用的 searchsort 路由值。当我按名字对人员列表进行排序时,表单将以 HTML 形式呈现,如下所示:

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

按照预期,?sort=firstname 包含在操作中。但是,当我按下提交按钮(搜索)时,sort 参数丢失。新网址只有 ?search=...。我该如何解决这个问题?

最佳答案

当您查看输出 html 时,您会得到如下内容:

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

这似乎完全合法,您会期望像附加帖子输入查询这样的行为。然而这受到 HTTP 规范的限制。不会附加表单发布操作的查询字符串。这就是为什么您的查询参数在服务器端不起作用的原因。然而,我希望 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>
}

关于asp.net - Html.BeginForm 在提交时丢失了routeValues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23425801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com