I have a bilangual MVC 3 application. I use a dropdownlist to change the language by saving the value of the dropdownlist into cookie and session. the problem is when I release it, it works only in IE. following is my code. note: the site will be reloaded and when I close firefox or chrome and reponed it, the language has been changed but nothing happend if I dont close FF or chrome. thank you very much for your help.
I have used $.get, $.post every kind of combinations.
JavaScript code:
$(function () {
$('#languagesDiv select').change(function () {
var myvalue = $(this).val();
$.ajax({
type: "POST",
dataType: "xml",
url: "/Language/SetLanguage",
data: { code: myvalue },
success: function (data) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
// @* $.post('@Url.Action("SetLanguage", "Language")', { code: $(this).val() },
// function (result) {
// }
// );*@
var myDate = new Date();
myDate.setDate(myDate.getDate() + 21);
$.cookie('MyData', $(this).val(), { path: '/', expires: myDate });
//window.location.reload();
window.location.href = '/News/Index';
});
});
C# code:
//tested with and without [httppost]
public void SetLanguage(string code)
{
if (Session["MyCulture"] != null && Convert.ToString(Session["MyCulture"]) != code )
{
Session["MyCulture"] = code;
HttpCookie aCookie = Request.Cookies["MyData"]; // new HttpCookie("MyData");
aCookie.Value = code;
//HttpCookie aCookie = Request.Cookies["LangCookie"];
aCookie.Expires = System.DateTime.Now.AddDays(21);
Response.Cookies.Add(aCookie);
//Response.AppendCookie(aCookie);
}
//return RedirectToAction("Index", "News");
}
Thank you again.
The problem I see (there could be others with the backend) is that your AJAX request likely won’t complete in the other/newer browsers. When you call this:
…you’re telling the browser to navigate away, this means it’s instantly going there, regardless of whether that previous AJAX request completed (the browser will likely kill the request early and move on).
Instead, you should redirect after that request completes and do the re-direct in your
successhandler, like this:This way you’re only telling the user to change pages after you’ve successfully made a request to change the language.