Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Peter Cort Larsen 388 posts 922 karma points
    Sep 21, 2018 @ 08:51
    Peter Cort Larsen
    0

    Call function from link in razor

    Hi,

    I have a link in a Macro Partial.

    <a href='@ChangeLanguage("sv-SE")'>SV</a>
    

    How do I invoke a method like this?

     public  void ChangeLanguage(string lang)
    {
    
        Thread.CurrentThread.CurrentCulture =
           CultureInfo.CreateSpecificCulture(lang);
        Thread.CurrentThread.CurrentUICulture = new
            CultureInfo(lang);
    
    }
    
  • Dan Diplo 1505 posts 5911 karma points MVP 4x c-trib
    Sep 21, 2018 @ 12:57
    Dan Diplo
    0

    There's a couple of options.

    The quick'n'dirty version would be to have your href pass in a query string with the language name, so something like:

    <a href='./?lang=sv-SE'>SV</a>
    

    Then in your script you'd see if a query string is passed in and call your function:

    if (!String.IsNullOrEmpty(Request.QueryString["lang"]))
    {
       var lang = Request.QueryString["lang"];
      // call your function
      ChangeLanguage(lang);
    }
    

    In razor you can create a functions area you just for functions like this:

    @functions
    {
        public void ChangeLanguage(string lang)
        {
            Thread.CurrentThread.CurrentCulture =
               CultureInfo.CreateSpecificCulture(lang);
            Thread.CurrentThread.CurrentUICulture = new
                CultureInfo(lang);
    
        }
    }
    

    You'd want to maybe check the querystring lang is a valid language first.

    A nice way would be to maybe use a custom render controller to access the request and change the culture there - see https://our.umbraco.com/Documentation/Reference/Routing/custom-controllers

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies