0

I want to customize URL for my asp.net mvc application. Currently I am working on asp.net MVC 4.5

Case : 1

Current URL : localhost/Country/Index/param1
Expected URL : localhost/param1 

Case : 2

Current URL : (1) localhost/Country/Index/param1 (Param1 is name of country)
              (2) localhost/State/Index/param11  (param11 is name of state)

Expected URL : localhost/param1/param11 (I need second url like this.)

Thanx in Advance.

Ashrafali
  • 9
  • 6
  • You cant. You need some way to distinguish your controller and action methods (unless you create a constraint that can look up a repository to check that `param1` matches an existing country). You could however generate a url which is say `../Country/param1` by defining specific routes –  Mar 18 '17 at 04:19
  • Thanx Stephen.. Is "case -1" is possible? – Ashrafali Mar 18 '17 at 04:33
  • Well both are possible, but it means creating a route constraint that looks up a database of your Countries and validating that the value of `param1` is a valid country. But that will be called on every request so its not really a good idea. –  Mar 18 '17 at 04:40
  • If you really do want to do this, then refer [this answer](http://stackoverflow.com/questions/37358416/routing-in-asp-net-mvc-showing-username-in-url/37359345#37359345) for an example –  Mar 18 '17 at 04:45
  • But it would be far easier if you accepted url's such as `../Country/Australia` and `../Country/Australia/Sydney` –  Mar 18 '17 at 04:48
  • I created separate route for all methods and routes – Ashrafali Apr 27 '17 at 13:34

2 Answers2

0

ASP.net MVC process the request based on the routing.The routing works on the data fetched from the rout table . So basically you have to have at least controller and action.But mvc provide us the option of changing the URL as below:

routes.MapRoute(
                name: "Test",
                url: "myURl/{param1}",
                defaults: new { controller = "myURl", action = "actualActionName", id = UrlParameter.Optional }
            );

in MVC5 same can be done by attribute routing.

0

To achieve your result, just create separate router for each event.

Currently may be you are using default routes like below.

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

Or try to create some different routes.

My suggestion is create seprate route for every event. like : Create a route with param1 and param11 to get desired result.

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

same create for another events and methods.

MohammedAshrafali
  • 499
  • 3
  • 8
  • 22