首页 > 解决方案 > 如何在 MVC 和 C# 中路由多个参数

问题描述

我的默认 MVC 路由设置为:

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

我想要做的是在我的搜索控制器命中有以下路线。

.../Search/Uk
.../Search/Uk/County/Buckinghamshire
.../Search/Uk/City/London
.../Search/Uk/Town/Ashford
.../Search/Uk/Postcode/AB-Aberdeen

我只有一个名为“索引”的视图。据我了解路由,我认为我应该能够做这样的事情:

public ActionResult Index(string country)

public ActionResult Index(string country, string searchType, string location)

但是没有雪茄,任何人都明白我做错了什么,我需要添加某种路线配置吗?事实上,我什至无法加载搜索页面

标签: c#asp.net-mvcroutesparameter-passing

解决方案


您可以使用基于属性的路由,您可以在路由本身中传递参数。

喜欢,

//I hope you have already enabled attribute routing and search controller with RoutePrefix as "search"

[Route("{country}")]
public ActionResult Index(string country)
{
  //Your business logic
}

[Route("{country}/{searchType}/{location}")]
public ActionResult Index(string country, string searchType, string location)
{
  //Your business logic
}

启用基于属性的路由:MSND


推荐阅读