asp.net-mvc - 搜索页面MVC路由(隐藏操作,没有斜线,像SO)

标签 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  

我的路线:

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/

相关文章:

asp.net-mvc - SiteMapPath - 通过路由和查询字符串传递参数

c# - 如何访问我的 LINQ 模型中的特定行?

jquery - 在其他对话框打开时更改 jquery 对话框标题的颜色,我们不希望它们更改

asp.net-mvc - 如何拥有移动版的 MVC 网站

asp.net-mvc-routing - Response.RedirectToRoute(RouteData.Values)重定向到Area Controller

asp.net-mvc - 用于搜索的ASP.NET MVC自定义路由

c# - 在本地谷歌地图上渲染 kml 文件?

c# - ASP.net MVC 自定义声明

asp.net-mvc - 为什么我的命名路线不起作用?

asp.net-mvc - 用于未知数量可选参数的 MVC 处理程序