MVC Routing: How to map two names to one action - c#

I'd like to have one route that gives the option of two urls but maps to one action. A good example would be for multilingual application. Lets take english and french for example.
This seems simple at first, technically you can do:
routes.MapRoute(
"the hi route english" ,
"welcome/sayhi/{id}" ,
new { controller = "Welcome" , action = "SayHi" , id = UrlParameter.Optional }
);
routes.MapRoute(
"the hi route french" ,
"bienvenu/direallo/{id}" ,
new { controller = "Welcome" , action = "SayHi" , id = UrlParameter.Optional }
);
But that means that you'll have to define two routes for every action. Or a little better solution, create a custom Route class that takes more params to handle bilingualism.
If I go option 1 or 2, It means I have to define every single routes of the WelcomeController because I cannot use {action} in my route.
Ideally, i'd like to be able to define at least action name via metadata and then grab it via reflection or something.
i.e.:
[ActionName( { "fr", "direallo" }, {"en", "sayhi"})]
public ActionResult SayHi(string id){
//check current thread culture...
}
I am not quite sure where to starts, any ideas? Tips?
Thank you,

You have several options starting points here, roughly they are (in order of implementation complexity):
A route per language (as you outlined above)
A regex route constraint e.g.
routes.MapRoute(
"the hi route",
"{controllerName}/{actionName}/{id}",
new { controller = "Welcome" , action = "SayHi" , id = UrlParameter.Optional },
new { controllerName = #"welcome|bienvenu", actionName = #"sayhi|direallo" }
);
You could create a base controller, which is inherited by a subclass per language and define a language specific action name for each base controller action method
You could create your own (or use the one provided in the answer to the comment by Justin Pihony) custom routing constraint

Related

Custom Routing without changing the URL

I have a controller and a view which returns book information when I pass the ID, e.g.:
/Content/Index?id=1
Now I want to make this as a friendly URL to end user. For eg:
Books/BookName (Name of the book the Id 1 is mapped to)
So I added a route values in global.asax as :
route.maprRoute(name:"custom", url:"Books/{bookname}",
defaults: new {controller = "bookMap", action ="index"}
in "BookMap" controller I get the bookname and convert that to the ID (which is 1)
and do a redirectionToAction to Content/Index by passing the ID as a parameter.
This works fine. But the problem is I want to keep the friendly name after redirecting to the view. Now it changes to Content/Index?id=1. But I want to keep the friendly URL which is Books/BookName. How do I achieve this pls.
You can use HttpContext.RewritePath(url) to do a redirect "internally" which keeps the external URL. Use this in place of the RedirectToAction. Note however that it's not properly supported by the MVC framework at this time so it will be a little "hacky" to implement.
You should change your route for this:
routes.MapRoute(
"Books",
"book/{bookname}/{bookid}",
new { controller = "book", action = "Index", bookname = UrlParameter.Optional },
new { id = #"\d+" }
);

MVC4: same url base for different actions

I would like to have 2 routes similar to these:
routes.MapRoute("Detail", "guide/{urlname}", new { controller = "Application", action = "Detail" });
routes.MapRoute("Search", "guide/{keyword1}/{keyword2}", new { controller = "Guide", action = "Index", keyword1 = UrlParameter.Optional, keyword2 = UrlParameter.Optional });
So one route is a detail page that looks up an object in the database based on its url name, and the other route is a search results page based on application-generated keywords, both of which share the same url root (/guide). The two actions are in different controllers. Possible urls are:
/guide/evernote --> should route to the application detail page
/guide --> should route to search results without filter
/guide/iphone --> should route to iphone apps search results
/guide/iphone/medical --> should route to medical iphone apps search results
Obviously, like this, the second route will never be matched for a url like /guide/iphone because the first route will already match the same url.
I don't want to do a redirect in the first action if the controller can't find the object in the database. So what other alternatives are there? Do I need to create a custom RouteHandler or UrlRoutingModule for this or is there a simpler way?
If {urlname} is a url like it implies, you can add a constraint to test if the url matches a regex:
http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-route-constraint-cs
Change the order and it will work:
routes.MapRoute("Search", "guide/{keyword1}/{keyword2}", new { controller = "Guide", action = "Index" });
routes.MapRoute("Detail", "guide/{urlname}", new { controller = "Application", action = "Detail" });

Dynamic ASP.net MVC Routing

I have a need for some dynamic routing. So my routes would look like this:
{UserName}
{UserName}/Edit/{id}
{UserName}/Delete/{id}
Where the users would be routed to the user controller. But I still want to maintain routes to controls like:
{Controller}/Edit/{id}
{Controller}/Delete/{id}
So basically I want it to direct to the physical controller say called OrdersController for edit delete but if someone navigates to /jdoe/ it sends it to the user controller.
How do I do this in my routes?
You need to create multiple routes, and keep them in the appropriate order
// one route for Users
routes.MapRoute("Users",
"{username}/{action}/{id}",
new { controller = "Users", action = "Index", username = string.Empty, id = UrlParameter.Optional },
new { id = #"\d+" }
);
// one route for everything else
routes.MapRoute("Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional},
new { id = #"\d+" }
);
It's not "really" as easy as above, but that's the jist of it. You would need too add a RouteConstraint to validate usernames.
Lastly, if you're using the username parameter, then why do you need the id? Just a thought.
Aside:
If you look at the user section here on StackOverflow, you'll see the routing look more like this.
users/{id}/{username}
users/{id}/edit
users/{id}/delete
I would personally say that this is a lot less work to achieve... but hey, that's just me.

MVC URL not rewriting

I'm trying to change the URL displayed in the user's browser from Happy/Balloons to happy-times/balloon-pops. There are many links in the project to the action "Balloons", so rather than change those links I'd like to change the global.asax so that a different URL appears for the same action. The original MVC Route looks like:
routes.MapRoute(
"Happy.Balloons",
"Happy/Balloons/{groupId}/{paymentType}/{mortgageValue}/{province}",
new { controller = "Happy", action = "Balloons" },
new { groupId = "\\d+", paymentType = "\\d+", mortgageValue = "\\d+", province = "\\d+" }
);
I've changed the code to
routes.MapRoute(
"Happy.Balloons",
"happy-times/balloon-pops/{groupId}/{paymentType}/{mortgageValue}/{province}",
new { controller = "Happy", action = "Balloons" },
new { groupId = "\\d+", paymentType = "\\d+", mortgageValue = "\\d+", province = "\\d+" }
);
I thought this second parameter was the URL displayed, but I'm getting a: "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable." error. Is there a simple way to do this by modifying parameters in MapRoute? If so, how?
Question Follow-up: Change URL of action in mvc
this works, (replacing urlParameter.Optional to default values)
routes.MapRoute( _
"Happy.Balloons", _
"happy-times/ballons-pops/{groupId}/{paymentType}/{mortgageValue}/{province}", _
New With {.controller = "happy", .action = "Balloons", .groupId = UrlParameter.Optional, .paymentType = UrlParameter.Optional, .mortgageValue = UrlParameter.Optional, .province = UrlParameter.Optional} _
)
but... it's a bad practice (really bad one)
you can learn about route maps here
You're doing it wrong.
Changing the route mapping will not change the name of the controller. Change the controller and action name, and map your route as {controller}/{action} like it is by default. Then you can set your default controller and action as you have before.
Then your controller will have to be renamed to happy-times and your action renamed to balloon-pops
I should note that it will look more like this:
{controller}/{action}/{groupId}/{paymentType}/{mortgageValue}/{province}
Here's a good resource on the topic.
http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs
as brought to you by this SO post https://stackoverflow.com/a/2375293/1178921
**Looks like you might be trying to see more ways to do this.
This post talks about attributes you can use to route URLS differently.
ASP.NET MVC Routing Via Method Attributes
Additionally, your way of changing the url in the mapping CAN work, but isn't what I thought your intent was. Zach dev had this one dead on in that case. Your optional parameters need to be marked as such with UrlParameter.Optional

mvc routes to share the same action?

I have the following two routes defined in my MVC app.;-
At the moment I have two "MVC View content pages" defined
/ShowName/NameById
/ShowName/Index
However the content on these two pages are identical? Is it possible for two routes to share the same content page? If not then can I a) create a single rule for both routes or b) should I create a usercontrol to share between both content pages to show my data?
routes.MapRoute(
"NameById",
"Name/{theName}/{nameId}",
new
{
action = "NameById",
controller = "ShowName",
theName = "Charley"
}
,new { nameId = #"\d+" }
);
routes.MapRoute(
"ShowName",
"Name/{theName}",
new
{
action = "Index",
controller = "ShowName",
theName = "Charley"
}
);
EDIT
I have read the answers below and I have the following action result methods. If I remove one of the methods (e.g. the Index) then how would I rewrite my routes to a single route?
public ActionResult Index(string theName)
public ActionResult NameById(string theName, int? nameId)
So the following works url's work?
/Name/Charley
/Name/Charley/11234
You could create a partial view for the detail area of the page, keeping the separation of the two actions in case they change at a later point. Or you could just
return View("DetailView", model);
But that can introduce an extra string to manage between the two controller actions. Since MVC does not support overloading by action name (unless you have a GET/POST pair, one with no arguments), you could just check the {nameId} parameter and see if it is empty/null before using it.
Do you really need 2 different routes? You could make the pattern for your Index route
Name/{theName}/{nameId}
and make nameId a nullable input to your action. Then just add some logic to your action which checks whether nameId has a value and acts accordingly.

Categories

Resources