0

I have a custom route setup in MVC4 which allows for a pattern like:

culture/controller/action/id

in addition to the default:

controller/action/id

I want to add a menu to my page that displays the available cultures. When a user clicks a culture, an identifier for "culture" should be inserted / updated into the URL?

What is the BEST way to modify the route (url) like this in MVC4?

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
user2121236
  • 53
  • 2
  • 7

1 Answers1

0

Make an HtmlHelper

public static class UrlExtensions
{
    public static MvcHtmlString CultureUrl(this HtmlHelper htmlHelper, string cultureName)
    {
        RequestContext requestContext = htmlHelper.ViewContext.RequestContext;

        RouteValueDictionary values = requestContext.RouteData.Values;

        var data = new
        {
            culture = cultureName ?? Thread.CurrentThread.CurrentUICulture.Name,
            controller = values["controller"],
            action = values["action"],
            id = values["id"]
        };

        UrlHelper urlHelper = new UrlHelper(requestContext);
        string url =  urlHelper.RouteUrl(data);

        return MvcHtmlString.Create(url);
    }
}

Then use it in the view:

<%foreach(var culture in Model.cultures){%>
    <%=Html.CultureUrl(culture)%>
<%}%>
Jani Hyytiäinen
  • 5,293
  • 36
  • 45
  • I am not getting this to work? On the line culture = cultureName ?? Thread.CurrentThread.CurrentUICulture.Name; the ; is underlined with an error of Synatax error, ',' expected. I also see errors of The name 'controller' does not exist in the current context. The name 'action does not exist in the current context, etc. – user2121236 Feb 28 '13 at 22:09
  • Semicolons fixed to commas – Jani Hyytiäinen Feb 28 '13 at 22:14
  • I swear I tried changing the semicolons to commas, but must be "Intellisense" was being a bit slow. Anyway, not I get an error on string url = UrlHelper.RouteUrl(data); of "An object reference is required for the non-static field, method, or property 'System.Web.Mvc.UrlHelper.RouteUrl(object)'" – user2121236 Feb 28 '13 at 22:24
  • And when I try to reference it, I get "No Overload for Method 'CultureUrl' takes 1 arguments" – user2121236 Feb 28 '13 at 22:48
  • You need to have it in a static class. I have fixed the example accordingly. – Jani Hyytiäinen Mar 01 '13 at 06:55
  • Jani, thanks... when I try to call it from a model, I still am getting "No overload for method CultureUrl takes 1 arguments). I get that the second argument is the culture name. What would I use for the first argument? – user2121236 Mar 01 '13 at 14:48
  • See the example, use it in the view. The HtmlHelper is the first argument. – Jani Hyytiäinen Mar 01 '13 at 18:48