如何在MVC和C#中路由多个参数?

问题描述 投票:0回答:2

我有我的默认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

我只有一个名为 "Index "的视图。由于我对路由的理解,我认为我应该可以做到这样的事情。

public ActionResult Index(string country)

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

但是没有人知道我做错了什么吗? 我需要添加一些路由配置吗?事实上,实现这个功能后,我甚至无法加载搜索页面。

c# asp.net-mvc routes parameter-passing
2个回答
1
投票

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

比如

//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

© www.soinside.com 2019 - 2024. All rights reserved.