简体   繁体   English

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

[英]How to route multiple parameters in MVC and C#

I have my default MVC routes setup as:我将默认 MVC 路由设置为:

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

What I want to be able to do is have the following routes in my Search controller hit.我想要做的是在我的搜索 controller 命中有以下路线。

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

I only have one view called "Index".我只有一个名为“索引”的视图。 As I understood routing I presumed I should of been able to do something like this:据我了解路由,我认为我应该能够做这样的事情:

public ActionResult Index(string country)

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

But no cigar, anyone understand what I'm doing wrong, do I need to add in some sort of routes configuration?但是没有雪茄,任何人都明白我做错了什么,我需要添加某种路线配置吗? Infact implementing this I cannot even load the search page事实上,我什至无法加载搜索页面

You can use attribute based routing where you can pass parameters in the route itself.您可以使用基于属性的路由,您可以在路由本身中传递参数。

like,喜欢,

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

Enabling Attribute based routing: MSND 启用基于属性的路由:MSND

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM