【问题标题】:How to route multiple parameters in MVC and C#如何在 MVC 和 C# 中路由多个参数
【发布时间】:2020-05-05 17:05:10
【问题描述】:

我的默认 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-mvc routes parameter-passing


    【解决方案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
    }
    

    Enabling Attribute based routing : MSND

    【讨论】:

    • 我好像没有WebApiConfig类,我有BundleConfig、FilterConfig、IdentityConfig、RouteConfig、Startup.Auth
    • 查看你的RouteConfig类,你的routes.MapRoute()写在哪里?
    • 我的设置也需要这个 [Route("{Search}/{country}/{searchType}/{location}")]
    • 请查看我的评论,如果您希望控制器名称应该在路由中,最好使用RoutePrefix
    猜你喜欢
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    相关资源
    最近更新 更多