我希望我的搜索像 Stack Overflow 中的搜索一样(即没有操作,没有斜杠):
mydomain.com/search --> goes to a general search page
mydomain.com/search?type=1&q=search+text --> goes to actual search results
我的路线:
routes.MapRoute(
"SearchResults",
"Search/{*searchType}", --> what goes here???
new { action = "Results" }
);
routes.MapRoute(
"SearchIndex",
"Search",
new { action = "Index" }
);
我的 SearchController 有以下操作:
public ActionResult Index() { ... }
public ActionResult Results(int searchType, string searchText) { ... }
搜索结果路由不起作用。我不想使用每个人似乎都在使用的“.../...”方法,因为搜索查询不是资源,所以我希望查询字符串中的数据如我所指示,而不需要斜杠——就像SO一样。
TIA!马特
最佳答案
您不需要两条路线,因为您将搜索参数作为查询字符串提供。只有一条搜索路线:
routes.MapRoute(
"Search",
"Search",
new { controller = "Search", action = "Search" }
);
然后编写这个 Controller Action
public ActionResult Search(int? type, string q)
{
var defaultType = type.HasValue ? type.Value : 1;
if (string.IsNullOrEmpty(q))
{
// perform search
}
// do other stuff
}
此方法的主体很大程度上取决于搜索条件,您在搜索内容时是否需要两个参数,或者仅需要 q
并且您有一些默认的 type
。请记住,页面索引可以用同样的方式完成。
使用强类型参数(明智的验证)
您当然可以创建一个可以验证的类,但属性名称应该反射(reflect)查询字符串的名称。所以你要么上一个类:
public class SearchTerms
{
public int? type { get; set; }
public string q { get; set; }
}
并像现在一样使用具有相同名称的查询变量的相同请求,或者使用一个干净的类并调整您的请求:
public class SearchTerms
{
public int? Type { get; set; }
public string Query { get; set; }
}
http://domain.com/Search?Type=1&Query=search+text
关于asp.net-mvc - 搜索页面MVC路由(隐藏操作,没有斜线,像SO),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5075765/