简体   繁体   中英

How to maintain TempData when calling a RedirectToAction to another controller

In a MVC 5 project, I have the following method in my controller;

public ActionResult Login(User user)
{
    TempData["User"] = null;

    if (ModelState.IsValid)
    {
        if (user.IsValid(user.Email, user.Password, Request.UserHostAddress))
        {
            string userData = user.Email;
            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(user.Email, false);
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
            FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);
            authCookie.Value = FormsAuthentication.Encrypt(newTicket);
            Response.Cookies.Add(authCookie);

            TempData.Keep("CmsContent");
            return RedirectToAction("Index", "ManageAccount");
        }
        else
        {
            TempData["User"] = user;
            TempData.Keep("CmsContent");
            return RedirectToAction("Index", "Home");
        }
    }
    else
    {
        user.Message = "Invalid email/password";
        TempData["User"] = user; 
        TempData.Keep("CmsContent");
        return RedirectToAction("Index", "Home");
    }
}

Rather than having to keep repeating the code below to maintain the TempData, (as I will need to maintain TempData["CmsContent"] in my other controller Actions as well) like

TempData.Keep("CmsContent");

How can I call a Controller action, on another controller, whilst maintaining this TempData

As in the comments Session is an answer for the particular question, but there might be reasons that you want to avoid it. I've used Brock Allen's solution in the situation where you'd like the convienence of TempData but don't want to make use of server sessions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM