-1

I have to send message from controller 1 to controller 3 and finally send to the view.
controller 1

public ActionResult controller1()
{
    TempData["data"] = "work finish.";
    return RedirectToAction("logoff");
}

Then in the controller 2

    public ActionResult logoff()
    {
        AuthenticationManager.SignOut();
        Session.Abandon();
        return RedirectToAction("index");
    }

Controller 3

    public ActionResult index()
    {
        ViewBag.data = TempData["data"] as string;
        return View();
    }

In the view page

<span>@ViewBag.data</span>

returning empty message. Thanks in advance.

anand
  • 1,559
  • 5
  • 21
  • 45
  • `TempData` uses `Session`. Move the `ViewBag.data = TempData["data"] as string;`line before you destroy `Session` –  Feb 25 '16 at 11:40

1 Answers1

-2

You should avoid TempData in this case. If you know you are going to need the value in more than 1 controller action then TempData is not for you because it will be erased once you access it (disclaimer: if you use Peek() it will be persisted but that's no the discussion).

What I think can work for you is to redirect with a parameter in your URL according to the result of the operation. You can do something like this:

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
    switch (result)
    {
        case SignInStatus.Success:                    
            TempData["data"] = "Login Success";
            return RedirectToAction("Action", new { loginSuccessful = true });
        default:
            ModelState.AddModelError("", "Invalid login attempt.");
            return View(model);
    }
}

Then in controller2 you would have your code like this:

public class SampleController : Controller
{
    public SampleController()
    {

    }

    public ActionResult Index(bool loginSuccessful)
    {
        if (loginSuccessful)
        {
            ViewBag["message"] = "Login successful";
        }
        return View();
    }
}

If any other controller action needs that parameter you just add it to the function signature as I did in the Index action and it will work as long as the parameter is still in the URL.

Felipe Correa
  • 654
  • 9
  • 23
  • @anand Maybe I don't get it well enough. If you can explain some more it would be great. I think my answer covers what you are asking as it is explained. If I can help let me know. – Felipe Correa Feb 25 '16 at 08:26