加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 03:51:53 所属栏目:asp.Net 来源:网络整理
导读:我希望我的搜索类似Stack Overflow中的搜索(即没有动作,没有斜线): mydomain.com/search -- goes to a general search page mydomain.com/search?type=1q=search+text -- goes to actual search results 我的路线: routes.MapRoute( "SearchResults","Sear
我希望我的搜索类似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",new { controller = "Search",action = "Search" }
);

然后编写此控制器操作

public ActionResult Search(int? type,string q)
{
    var defaultType = type.HasValue ? type.Value : 1;
    if (string.IsNullOrEmpty(q))
    {
        // perform search
    }
    // do other stuff
}

这种方法的主体在很大程度上取决于搜索条件,当你搜索东西时你是否需要这两个参数,或者你是否有类型的默认值.请记住,页面索引可以以相同的方式完成.

使用强类型参数(验证明智)

您当然可以创建一个可以验证的类,但属性名称应该反映查询字符串的类.所以你要么上课:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读