Monday, 19 May 2014

ASP MVC Cookie not working properly

I was working on cookie to change my website theme. My intention was to save theme name in cookie variable. It can be done by JQuery too but I was trying with .NET.

What was my problem scenario:

After setting the cookie variable I returned a View() but it didn't change the theme :( if reload the page againg then theme changed as expected. that means cookie was actually setting correctly.

my Server side code was like this -

     public ActionResult ChangeTheme(string themename = "") //hope you know how to call this ChangeTheme method.
        {
            HttpCookie cookie = new HttpCookie("Theme");
            cookie.Values["ThemeName"] = themename;
            cookie.Expires = DateTime.Now.AddDays(365);
            Response.Cookies.Add(cookie);
            return View("Index"); // this line will be changed
        }

Solution:

Index view was returning but theme was not changing first time. I changed that line -

            return RedirectToAction("Index", "Home");

Now everything is fine. theme is changing after reloading the page.

No comments:

Post a Comment