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 418 posts 1015 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 1554 posts 6205 karma points MVP 5x 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

Please Sign in or register to post replies

Write your reply to:

Draft