Reading Umbraco dictionary item in Ajax request
The workaround for getting proper dictionary value in Ajax request
You probably had to make some Ajax call in your Umbraco website. This is really easy in versions star6ting from version six and above. All you need to to is to inherit surface controller in your controller class as shown in following snipped.
public class HomeController : Umbraco.Web.Mvc.SurfaceController { }
Problems start if your result (usually partial view) needs to include some value from dictionary.
The root cause of this is that thread on which Ajax request is executed does not inherit website UI culture.
Culture of Ajax request thread is neutral and therefore you will probably get English value for every dictionary regardless of the current language on your website.
The solution I found for this is to send the culture LCID to the invoked controller method. The following line is to fetch the current UI culture LCID
System.Threading.Thread.CurrentThread.CurrentUICulture.LCID
Now you need to include it as a parameter in your JQuery Ajax call and pump in LCID value.
$.post("/umbraco/Surface/Home/GetSomeData", { CultureId: "@System.Threading.Thread.CurrentThread.CurrentUICulture.LCID" }, function (data) { //Put returned partial view html to some container like div });
Now you just need to set the current thread UI culture
public class HomeController : Umbraco.Web.Mvc.SurfaceController { [HttpPost] public ActionResult GetSomeData(int CultureLCID){ System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(CultureLCID); Umbraco.Web.UmbracoHelper helper = new Umbraco.Web.UmbracoHelper(Web.UmbracoContext.Current); string dictionaryValue = helper.GetDictionaryValue("DictionaryValuekey"); //Return partial view here } }
Returned partial view Razor will be executed on the same thread as controller method, so that means that UI culture is inherited from controller thread.
This means that fetching dictionary values in returned partial view will be correct.
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article