当有很多参数时,MVC 自定义路由不起作用

本文关键字:MVC 自定义 路由 不起作用 参数 | 更新日期: 2023-09-27 18:33:36

我在MVC中设置自定义路由时遇到很多问题

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
                "SearchList",
                "Search/{city}/{cat}", // URL
                new
                {
                    controller = "Search",
                    action = "Index"
                }, // URL Defaults
               new { id = @"'d+" }
            );

搜索控制器

public ActionResult Index(string city, string search, string cat, int? pageNo, string ratio, string fee, string curr, int? id)

此方法用于搜索带有过滤器的特定项目。

我尝试了很多排列组合,但没有成功。

我需要以下类型的结果:

http://localhost/Search/City/Category
http://localhost/Search/City
http://localhost/Search/Category
http://localhost/Search/Curr

当我输入以下 url 时,我收到"在控制器'App.Web.Controllers.SearchController'上找不到公共操作方法'pune'"错误:

http://localhost:5355/Search/pune/Preschool

当有很多参数时,MVC 自定义路由不起作用

您的搜索确实不应该使用路由级参数,而应该使用查询字符串。这就是它的用途,查询

在使用路由参数进行搜索时会遇到问题,因为对于 MVC 路由,只能使最后一个路由参数成为可选参数。其余的都是必需的。

使用如下所示

的URL会更好:

http://localhost:5355/Search?City=pune&Category=Preschool

不过,@theDarse关于您看到的异常消息是正确的。在路由配置中的某个位置,您拥有默认路由。确保在SearchList路由之后定义它。

你为什么不考虑使用Area,这样会更容易,我不确定你是否可以这样做,我从来没有这样做过。