Mat*_*tt0 6 asp.net-mvc asp.net-mvc-routing
我希望我的搜索类似于Stack Overflow中的搜索(即没有动作,没有斜线):
mydomain.com/search --> goes to a general search page
mydomain.com/search?type=1&q=search+text --> goes to actual search results
Run Code Online (Sandbox Code Playgroud)
我的路线:
routes.MapRoute(
"SearchResults",
"Search/{*searchType}", --> what goes here???
new { action = "Results" }
);
routes.MapRoute(
"SearchIndex",
"Search",
new { action = "Index" }
);
Run Code Online (Sandbox Code Playgroud)
我的SearchController有以下动作:
public ActionResult Index() { ... }
public ActionResult Results(int searchType, string searchText) { ... }
Run Code Online (Sandbox Code Playgroud)
搜索结果路线不起作用.我不想使用每个人似乎都在使用的".../..."方法,因为搜索查询不是资源,所以我希望查询字符串中的数据如我所指出的那样,没有斜线 - 就像SO一样.
TIA!马特
您不需要两条路线,因为您提供搜索参数作为查询字符串。只有一条搜索路线:
routes.MapRoute(
"Search",
"Search",
new { controller = "Search", action = "Search" }
);
Run Code Online (Sandbox Code Playgroud)
然后编写这个控制器动作
public ActionResult Search(int? type, string q)
{
var defaultType = type.HasValue ? type.Value : 1;
if (string.IsNullOrEmpty(q))
{
// perform search
}
// do other stuff
}
Run Code Online (Sandbox Code Playgroud)
此方法的主体很大程度上取决于搜索条件,无论您在搜索内容时需要这两个参数,还是仅q需要一些默认值type。请记住,页面索引可以用同样的方式完成。
您当然可以创建一个可以验证的类,但属性名称应该反映查询字符串的名称。所以你要么上一堂课:
public class SearchTerms
{
public int? type { get; set; }
public string q { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
并像现在一样使用具有同名查询变量的相同请求,或者使用一个干净的类并调整您的请求:
public class SearchTerms
{
public int? Type { get; set; }
public string Query { get; set; }
}
http://domain.com/Search?Type=1&Query=search+text
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
794 次 |
| 最近记录: |