ASP.Net MVC 路由无法正常工作
我们的 Global.asax.cs 文件中有几条路线,但其中一条显然没有被使用。
// Search (NOT working).
routes.MapRoute(
"Search",
"search/{query}",
new { controller = "Search", action = "Index" });
// Homepage (I believe the problem could be here, but not sure).
routes.MapRoute(
"MainIndex",
"{language}",
new { controller = "Main", action = "Index", language = string.Empty });
当我们在action属性为“/Search”的搜索表单中进行搜索时,用户将被发送到主页,并且地址栏中的URL为“/Search?query=example+search”。
表单操作属性是使用以下代码内置的:
<form id="form1" action="<%= Url.Action("Index", "Search") %>">
对我来说似乎是正确的,但操作名称应该是“/search”而不是“/Search”,对吗?
We have several routes in our Global.asax.cs file, but one of them is not apparently being used.
// Search (NOT working).
routes.MapRoute(
"Search",
"search/{query}",
new { controller = "Search", action = "Index" });
// Homepage (I believe the problem could be here, but not sure).
routes.MapRoute(
"MainIndex",
"{language}",
new { controller = "Main", action = "Index", language = string.Empty });
When we do a search in the search form which action attribute is "/Search", the user is sent to the homepage and the URL in the address bar is "/Search?query=example+search".
The form action attribute is built in using this code:
<form id="form1" action="<%= Url.Action("Index", "Search") %>">
Seems right to me, but the action name should be "/search" instead of "/Search", right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我刚刚使用以下视图
和这样的控制器
尝试了您的路线,并且工作正常。请注意,(1) 我使用的是 method=post 并且 (2) 文本框的名称和 ID 设置为“query”,这就是 Html.TextBox 会为您完成的操作。这就是允许绑定获取值并将其正确传递给控制器的原因。
I just tried your route with the following view
and a controller like this
and it works OK. Notice that (1) I am using method=post and (2) that the textbox has both a name and ID set to "query" which is what the Html.TextBox would have done for you. This is what allowed the binding to pick up the value and pass it correctly to the controller.
我总是发现这个工具对于调试路由非常有帮助。 路由调试器
I always find this tool extremely helpful in debugging routes. Route Debugger
尝试使
"search/{query}"
与大小写匹配 =>"Search/{query}"
那么您对表单标记的操作是
/Search/Index
,它将与您的Search/{query}
相匹配路线,但您的查询将是 Index.但是,如果?query=example+search
位于路由末尾,搜索路由将不知道如何处理该查询参数。我只需将表单标记上的操作属性更新为/Search
并且不使用 URL 帮助器。Try making the
"search/{query}"
match the case =>"Search/{query}"
Well your action on the form tag is
/Search/Index
, which will match yourSearch/{query}
route, but your query will be Index. However, with the?query=example+search
on the end of your route, the Search route won't know how to handle that query parameter. I would just update the action attribute on the form tag to just be/Search
and not use the URL helper.