如何让 Html.BeginForm 获取到正确的 MVC 路由
在我的 ASP.NET MVC 应用程序中,我有以下 GET 输入字段:
<% using (Html.BeginForm("Search", "Products", FormMethod.Get) { %>
<input type="text" name="searchQuery" id="searchQuery" />
<% } %
我希望它转到路由:
routes.MapRoute("ProductSearchRoute",
"Products/Search/{searchQuery}/{pageNumber}",
new { controller = "Products", action = "Search", pageNumber = 1 });
问题是,它作为查询字符串转到 /Products,例如 Products?searchQuery=Motoroil。如何让它使用我的 ProductSearchRoute 并改为形成 /Products/Search/Motoroil ?
In my ASP.NET MVC application I have the following GET input field:
<% using (Html.BeginForm("Search", "Products", FormMethod.Get) { %>
<input type="text" name="searchQuery" id="searchQuery" />
<% } %
I want this to go to the route:
routes.MapRoute("ProductSearchRoute",
"Products/Search/{searchQuery}/{pageNumber}",
new { controller = "Products", action = "Search", pageNumber = 1 });
The problem is, it goes to /Products as query string, e.g. Products?searchQuery=Motoroil. How do I get it to use my ProductSearchRoute and instead form /Products/Search/Motoroil ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果我理解正确的话,您是否正在尝试根据表单的输入动态更改表单发布的位置?
为此,您需要使用 javascript 来更改表单的目标属性。 BeginForm()用于渲染表单标签,从html角度来看,它是静态的。
If I understand you correctly, you're trying to dynamically alter the location the form posts to, based on the inputs of the form?
You'll need to use javascript for this, to alter the form's target attribute. The BeginForm() is for rendering the form tag, which from an html perspective, is static.
你可以尝试:
善良,
丹
You could try:
Kindness,
Dan
正如 @Daniel Elliott 建议的那样,使用 BeginRouteForm。要正确生成 URL,您必须使用路由表中定义的相同名称设置路由值。
As @Daniel Elliott suggested, use BeginRouteForm. To get your URL to generate properly, you have to set the routevalues with the same name defined in your route table.