21

I have started converting my simple website to ASP.NET MVC, just to mess around with it. I have a switch language feature on there that basically sets the Session["language"] to another language and refreshes the page. Please correct me if this could be done better, but I have made two controllers for this and setting the session in there. The problem is the routing at the end. Could I refresh the page in some neat way, or can I get the current Action and re-route it to that? Or is this more a scenario for Ajax?

Thankful for advice!

miccet
  • 1,870
  • 3
  • 19
  • 26

3 Answers3

21

is there any reason why you are using the session variable? a more common solution is to include the language code in the route, i.e. blah.com/en/info or blah.com/jp/info (for english and japanese)

if you did this every page on the site could contain links to each language. if you are writing a publicly accessible site this would also make it easier for google to index all your content.

this article explains how to include the language in the domain, ie. en.blah.com or jp.blah.com: http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx

UPDATED: Here's a simple example of including the language code in the URL route.

Change the default route to include a language parameter:

routes.MapRoute(
"Default", 
"{language}/{controller}/{action}/{id}", 
new { language = "en", controller = "Home", action = "Index", id = "" }
);

Add links for each language to your masterpage:

<li><%= Html.ActionLink(
    "Spanish", 
    ViewContext.RouteData.Values["action"].ToString(), 
    new { language = "es" })%></li>
<li><%= Html.ActionLink(
    "French", 
    ViewContext.RouteData.Values["action"].ToString(), 
    new { language = "fr" })%></li>
<li><%= Html.ActionLink(
    "English", 
    ViewContext.RouteData.Values["action"].ToString(), 
    new { language = "en" })%></li>    

These will render as links back to the page you are on - only with the language changed.

russau
  • 8,928
  • 6
  • 39
  • 49
  • I do it because of simplicity. I just have to write something like PageText.GetOneForMe("textKey"), and then the PageText decides from the session which language it is. You have some points here and I'm gonna experiment with it later on, don't worry I'll check in later and give you the creds if this works :) Thanks for now! – miccet May 30 '09 at 08:43
  • Hm, back again. I mean I understand this in theory, only, how would I change the links in a smart way? I mean they are the same links, but once I click a link it would have to switch it's url to the other language. The problem is also that if I'm on the "About" page, I want to refresh that page, only with the language switching, like some sort of reflection I guess.. – miccet May 30 '09 at 09:02
  • In my case the sentence ViewContext.RouteData.Values["action"].ToString() does not build. Visual Studio says: "Value of type 'System.Web.Routing.RouteValueDictionary' cannot be converted to 'String'" Why that? – Julen Jul 13 '11 at 14:13
  • Nice touch there. I have one question: here we generate outgoing links with `ActionLink` helper. Let's say our link has multiple Route Values like: `poo/bar/cat1/subcat2/producttype/product`. Here, we are able to put this parameters to the link as well. Is it because `ActionLink` helper inherits the current thread's route values? – tugberk Nov 27 '11 at 10:41
  • How do you do this using web form routing? – PsychoDUCK Apr 19 '12 at 16:50
  • 1
    This solution worked for me. BUT .. it only works once. If I click French, I get the page in french (after some logic in the controller). but the other links on the page still using the default EN. How can I permanently change the default language when I click on the ActionLink? – Yousi Nov 22 '12 at 03:56
  • This might be what you need. It is an extension to the actionlink helper so you can handle localized URLs [link](http://www.ryadel.com/en/html-actionlink-extension-method-written-c-handle-multi-language-routes-asp-net-mvc/) – freethinker6 Apr 21 '17 at 17:09
7

Following approach works good for me:

I'm using cookies and my own engine for localization All you need to put some link on the page that will redirect to something like this:

public class LanguageController : Controller
{
    //
    // GET: /Language/

    public void Change(string id)
    {
        var cuka = new HttpCookie("lang", id + "");
        cuka.Expires = DateTime.Now.AddYears(10);
        System.Web.HttpContext.Current.Response.Cookies.Add(cuka);

        if (Request.UrlReferrer.IsNotNull())
            Response.Redirect(Request.UrlReferrer.AbsoluteUri);
        else
            Response.Redirect("/");
    }

}

}

If you're interested in this engine, let me know.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
omoto
  • 1,212
  • 1
  • 17
  • 24
  • This is basically what I'm doing, only using the session. But I think you basically answered my question in the refresh to the current route. I'll try it tonight or tomorrow and get back here. Thanks! – miccet May 31 '09 at 14:38
  • `.IsNotNull()` seems to be an extension method. Could you provide the code? – BCdotWEB Apr 16 '20 at 15:14
0

there is a controller for the language management

    public class LocalesController : Controller
{

    public ActionResult Index(string lang = "en_US")
    {
        Response.Cookies["CacheLang"].Value = lang;

        if (Request.UrlReferrer != null)
            Response.Redirect(Request.UrlReferrer.ToString());

        var message = Localization.Get("changedlng");

        return Content(message);
    }

}

you can call it separately

new LocalesController().Index("fa");
Hamid Jolany
  • 800
  • 7
  • 11