Changing single route part of URL - c#

I have the following route:
routes.MapRoute(
"Default", // Route name
"{language}/{controller}/{action}/{id}",
new { language = "en", controller = "XY", id = UrlParameter.Optional }
);
For changing the language of the site, I would like to create links, which correspond exactly to the url of the current page, but have another language part.
What would be the best way, to generate such a link?

Most likely, you'll want to insert the {language} value as part of each link-rendering View's ViewModel or ViewData. There's a few different way you could achieve this; such as overloading your controller's OnActionExecuted() method. If you take this approach, I suggest making all of your controllers inherit from a single base controller.
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.Controller.ViewData["Language"] = GetUserLanguage();
base.OnActionExecuted(filterContext);
}
And then in your View:
#Url.Action("Index", "Home", new { language = ViewData["Language"] })
Alternatively, you might consider overloading the Url.Action() and Html.ActionLink() methods with logic which appends this value automatically.

You could do something like this:
#Html.RouteLink("Switch Language", "Default", new {
controller = ViewContext.RouteData.Values["controller"],
action = ViewContext.RouteData.Values["action"],
id = ViewContext.RouteData.Values["id"],
language = "fr"
})
It would probably make sense to make an extension method to handle this though.

Related

Drop Route Values on Redirect

So, I've been trying for a few hours now to workaround something that should theoretically be very simple. Let's take this sample url:
http://sample.com/products/in/texas/dallas
This maps onto a specific route:
routes.MapRoute(
"products",
"products/in/{state}/{city}",
new { controller = "Products", action = "List", state = UrlParameter.Optional, city = UrlParameter.Optional });
In my action method, I can do lookups to make sure "texas" and "dallas" exist, and that "dallas" exists within Texas. That's all fine and dandy. However, in the situation where the city doesnt exist (either because the geo is incorrect, or mispelled), I want it to back up the state level. Example:
http://sample.com/products/in/texas/dallax
That should issue a redirect to
http://sample.com/products/in/texas
The "easy" way to do this was to simply issue a Redirect call like so:
return Redirect("/products/in/" + stateName);
However, I'm trying to decouple this from the URL structure; for example, if we ever decided to change how the route looks (say, change the pattern to products/around/{state}/{city}), then I would have to know that I need to make updates to this controller to fix the URL redirect.
If I can make a solution that just inspects the route values and can figure things out, then I don't have to worry if I change the route pattern, because the route values could still be figured out.
Ideally, I would have liked to do something like this:
return RedirectToRoute(new { controller = "Products", action = "List", state = state });
(Note, that is is a simplified example; the "required" route pieces like controller name and action method name would be determined by Generic argument and Expression inspection respectively).
That actually performs the redirect, HOWEVER, the route values from the current request get appended onto the redirect and thus you get in a redirect loop (note that I didn't include the city route value in the route object). How do I stop the "city" route value from being included in this redirect?
I've tried the following things to get rid of the route value:
Compose my own RouteValueDictionary / anonymous route data object and pass that to the overload of RedirectToRoute.
Create my own action result to inspect RouteTable.Routes and find the route myself, and do the replacement of the tokens myself. This seems the most "kludgy", and would seem to be re-inventing the wheel.
Make a method like RedirectWithout that takes a key value and calls RedirectToRouteResult.RouteValues.Remove(key) - which also didnt work.
I've also attempted to add a null value for the key I don't want to add; however, this alters the route to something that isnt correct - ie new { controller = "Products", action = "List", state = stateName, city = (string)null } issues a redirect to /Products/List?state=Texas which is not the right URL.
It all seems to stem from the RedirectToRoute taking the current request context to construct the virtual path data. Is there a workaround?
If you were using T4MVC, you should be able to do something like this:
return RedirectToAction(MVC.Products.List(state, null));
Have you tried this?
return RedirectToRoute(new
{
controller = "Products",
action = "List",
state = state,
city = null,
});
Reply to comments
Maybe MVC is confused because your optional parameter is not at the end. The below should work with the above RedirectToRoute that specifies city = null:
routes.MapRoute(
"products",
"products/in/{state}/{city}",
new
{
controller = "Products",
action = "List",
// state = UrlParameter.Optional, // only let the last parameter be optional
city = UrlParameter.Optional
});
You can then add another route to handle URL's where state is optional:
routes.MapRoute(null, // I never name my routes
"products/in/{state}",
new
{
controller = "Products",
action = "List",
state = UrlParameter.Optional
});

ASP.Net MVC3/4 multiple templates

There is any way to change the defualt views path in MVC3/4. i.e: The Url http://localhost:000/Home (the controller Home) will represent the view at Views/Style1/Home/Action.
Thanks ahead!
Ok, now that I understand the question better after the edit, I think this is what you're looking for:
You can change the ViewLocation in Application_Start().
The example below assumes use of the Razor View Engine.
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine { ViewLocationFormats = new string[] { "~/Views/Style1/{1}/{0}.cshtml" } } );
Answer was partially derived and referenced from this post
You should be able to set the Default route for your application to use a different base path. You can typically set the route in the Global.asax in the RegisterRoutes method.
Example:
routes.MapRoute(
"Default", // Route name
"Style1/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

MVC Routing: How to map two names to one action

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

How this controller can get the values it needs?

Say I have set up a url structure as follows (ASP.NET MVC2)
http://localhost:XXXX/Product/
Click on link browse by color
http://localhost:XXXX/Product/Color/
Click on link browse red color items by type (i.e. pen's)
http://localhost:XXXX/Product/Color/Red/Pen
In the controller, I will need to do a select based on these criteria. Except when previously, I could go
public ActionResult ShowTypesForColor(string color)
but to do this one:
public ActionResult ShowItems(string type)
I also need the color that was selected.
How could I do this? Is splitting up the url string the only way?
edit: maybe i've gotten ahead of myself in the global.asax.cs
routes.MapRoute(null, "Product/Color/", new { controller = "Product", action = "ShowAllColors" });
routes.MapRoute(null, "Product/Color/{color}", new { controller = "Product", action = "ShowTypesForColor" });
routes.MapRoute(null, "Product/Color/{color}/{type}", new { controller = "Product", action = "ShowDetail" });
I don't think I can define the last one like that can I? with two {} values?
Your last route seems perfectly valid. It will map to action with signature like this:
ActionResult ShowDetails(string color, string type) {
return View(/*view params*/);
}
EDIT I think the order is wrong, so if the last route is not being fired, try doing this:
routes.MapRoute(null, "Product/Color/{color}/{type}", new { controller = "Product", action = "ShowDetail" });
routes.MapRoute(null, "Product/Color/{color}", new { controller = "Product", action = "ShowTypesForColor" });
routes.MapRoute(null, "Product/Color/", new { controller = "Product", action = "ShowAllColors" });
The order of MVC routes should be from most specific to least specific, otherwise the least specific route (/product/color/{color}) will match a url product/color/red/pen before the more specific /product/color/{color}/{type}
You can put multiple tokens in your route (e.g., {color} and {type}) but it's not going the work the way you have it there. Why have you defined "Color" as the second segment of your URL? Why not just do /Products/Red and /Products/Red/Pen? It's inconsistent to do .../Colors/Red and not .../Types/Pen so I'd just leave the "Colors" and "Types" qualifiers out altogether.
I'd define your ShowItems() method like this:
public ActionResult ShowItems(string color, string type)
this will allow you to have a route like /Products/Red/Pen where your route maps to this ShowItems() method. But you'll still need to differentiate that from the ShowTypesForColor() method where it also takes a first parameter of color. The routing framework will just treat type as null - for the route that has both tokens, make sure you have a route constraint specifying that neither color nor type can be null/empty (i.e., for the ShowItems() route).

MVC Custom Routing

I'm new to MVC. I'm having trouble trying to accomplish having a route setup in the following manner:
System/{systemName}/{action}
Where systemName is dynamic and does not have a "static" method that it calls. i.e.
http://sitename.com/Systems/LivingRoom/View
I want the above URL to call a method such as,
public void RouteSystem(string systemName, string action)
{
// perform redirection here.
}
Anyone know how to accomplish this?
routes.MapRoute(
"Systems_Default",
"System/{systemName}/{action}",
new { controller="System", action = "RouteSystem", systemName="" }
);
Should route your request as you specified.
Note that with the above route, your Url should be:
http://sitename.com/System/LivingRoom/View
I had a similar problem. I used the following route.
routes.MapRoute(
"BlogSpecific", // Route name
"{blogSubFolder}/{controller}/{action}/{id}", // URL with parameters
new { blogSubFolder = "", controller = "", action = "", id = "" } // Parameter defaults
);
blogSubFolder just gets passed to my controller actions as a parameter. Controller and action all work just as they usually do. Just swap out blogSubfolder with your "System" paramter and that will hopefully work for you.
It looks like you intend to route to a controller based on the system name. If that is correct then you would simply need this:
routes.MapRoute("Systems",
"Systems/{controller}/{action}"
new{controller = "YourDEFAULTController", action = "YourDEFAULTAction"});
Please note that the third line only sets the default values specified if they are NOT included in the url.
Given the route above, MVC would route this:
http://sitename.com/Systems/LivingRoom/View
to the View action method on the LivingRoom controller. However this:
http://sitename.com/Systems/LivingRoom
would route to the YourDEFAULTAction method on the LivingRoom controller.

Categories

Resources