简体   繁体   English

ASP.MVC 4 - 在Url中使用First QueryString参数并附加到Action

[英]ASP.MVC 4 - Using First QueryString Parameter & Append to Action in Url

I'd like to tidy this url if at all possible. 如果可能的话,我想整理这个网址。

Curently it looks like this which is returned from an ActionResult GET 从某个ActionResult GET返回它看起来像这样

http://localhost/Controller/Action?City=SomeCity&GeoLat=00.000&GeoLong=-0.00000494

Here's what I'm trying to achieve 这就是我想要实现的目标

http://localhost/Controller/Action/SomeCity?GeoLat=00.000&GeoLong=-0.00000494

The City parameter isn't used for anything, so manually editing the first url into the second does indeed return the correct data. City参数不用于任何内容,因此手动将第一个url编辑到第二个URL确实会返回正确的数据。

I've even tried appending int the City variable to the action, not really ideal. 我甚至尝试将City变量附加到动作中,而不是非常理想。

routes.MapRoute(
                "Default",
                "{controller}/{action}-{City}/",
                new { controller = "House", action = "Location", City = UrlParameter.Optional }
                );

Thanks! 谢谢!

You were almost there with the routing change. 路由变化几乎就在那里。 Add this code BEFORE the default route 在默认路由之前添加此代码

routes.MapRoute(
    "CityRoute",
    "{controller}/{action}/{City}",
    new { controller = "House", action = "Location" }
);

Note that I change the url format slightly and removed the optional parameter part (it's not needed) 请注意,我稍微更改了url格式并删除了可选参数部分(不需要)

as I correct understand, this will be solution for you: 正如我所理解的那样,这将是您的解决方案:

        routes.MapRoute(
            name: "City",
            url: "House/Location/{City}",
            defaults: new { controller = "House", action = "Location" }
        );

Controller: 控制器:

[HttpGet]
public ActionResult Location(string City, string GeoLat, string GeoLong){  }

what is more - you have to add this before default route: 更重要的是 - 你必须在默认路由之前添加它:

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

at least, now you will be able to achieve GeoLat and GeoLong value, as also City parametr, in your controller method. 至少,现在您将能够在控制器方法中实现GeoLatGeoLong值,以及City parametr。

To get the url you're after in MVC 4 you have two options 要获得你在MVC 4中获得的网址,你有两个选择

  1. Map a route with a city param: 使用city参数映射路线:

     routes.MapRoute( "City", "{controller}/{action}/{city}", new { controller = "House", action = "Location", city = UrlParameter.Optional } ); 
  2. Rename you city param to id and use the default route mapping. city参数重命名为id并使用默认路由映射。

(MVC 5 introduces the RouteAttribute class that allows you to specify mappings on individual Actions.) (MVC 5引入了RouteAttribute类,允许您指定各个Actions的映射。)

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

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