简体   繁体   中英

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

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.

I've even tried appending int the City variable to the action, not really ideal.

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)

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.

To get the url you're after in MVC 4 you have two options

  1. Map a route with a city param:

     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.

(MVC 5 introduces the RouteAttribute class that allows you to specify mappings on individual Actions.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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