ASP.NET MVC 中的搜索路由
我的主页中有一个简单的搜索表单以及一个搜索控制器和视图。 我正在尝试获取字符串搜索词“myterm”的以下路径(例如): root/search/myterm
母版页中的表单:
<% using (Html.BeginForm("SearchResults", "Search", FormMethod.Post, new { id = "search_form" }))
{ %>
<input name="searchTerm" type="text" class="textfield" />
<input name="search" type="submit" value="search" class="button" />
<%} %>
控制器操作:
public ActionResult SearchResults(string searchTerm){...}
我正在使用的路线:
routes.MapRoute(
"Search",
"search/{term}",
new { controller = "Search", action = "SearchResults", term = (string)null }
);
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index" }
);
无论我输入什么搜索词,我总是得到不带搜索词的 url“root/search”。
谢谢。
I have a simple search form in my master page and a serach controller and view.
I'm trying to get the following route for the string search term "myterm" (for example):
root/search/myterm
The form in the master page :
<% using (Html.BeginForm("SearchResults", "Search", FormMethod.Post, new { id = "search_form" }))
{ %>
<input name="searchTerm" type="text" class="textfield" />
<input name="search" type="submit" value="search" class="button" />
<%} %>
The Controller Action:
public ActionResult SearchResults(string searchTerm){...}
The Route I'm Using :
routes.MapRoute(
"Search",
"search/{term}",
new { controller = "Search", action = "SearchResults", term = (string)null }
);
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index" }
);
I'm always getting the url "root/search" without the search term, no matter what search term I enter.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在 beginform 标记中使用 id ,在路线中使用 {term} 。
两者需要匹配。
You're using id in your beginform tag and {term} in your route.
The two need to match.
因此,如果我理解正确的话,您正在尝试制定一条路线,以便可以转到 http:// www.whatever.com/search/blah,您将被路由到 SearchResults 操作,其中 searchTerm 参数为“blah”。
以下路由将解决这个问题:
确保该路由位于默认路由之前,否则将首先匹配默认路由。请注意,“term”已更改为“searchTerm”以匹配操作中的参数。这是必要的。
So if I understand you correctly, you are trying to make a route so that you can go to http://www.whatever.com/search/blah and you will be routed to the SearchResults action with the searchTerm parameter being "blah".
The following route will take care of that:
Make sure the route is BEFORE the default route or the default will be matched first. Notice that "term" is changed to "searchTerm" to match the parameter in your action. This is necessary.