Question

I am trying to access C# Static Variable in JavaScript/JQuery in an MVC 4 application. I am able to access it with following syntax.

var currentCulture = '@StaticCache.Culture';  //Returns en-GB

Issue is that once page load I can access correct value but assuming we make one Ajax Call to server and that call (in Controller) change the value for static variable.

StaticCache.Culture="en-US";

Again read same static variable in Java Script (Razor View)

var currentCulture = '@StaticCache.Culture';  //**Still returns en-GB instead of en-US**

It cached the variable somehow. Is there any way I can read the latest value?

Thank you Best Regards.

Was it helpful?

Solution

If you're operating on AJAX, and something is being updated that needs to be reflected on the page, then you should return it in the response from your AJAX request.

Using that Razor syntax is only going to update those values when loaded from the server, as you've discovered. There's no way client side to know that the value has changed server side without the two communicating.

If you don't want to partially reload the page, or return it in the AJAX response, you can look at libraries like SignalR which keep a real-time communication channel available between the client and server (which will update your values via JavaScript once implemented.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top