Search code examples
asp.net-mvcviewbagviewdata

mvc-pass data from controller to view of other controller


I am having a AccountController in which I have an action YNHHConsentForm inside this action I am redirecting to another View using RedirectToAction("Index", "Default"). Now I want to show a message on Index page of Default. I have tried to pass value using ViewBag or ViewData but it remains null and I am unable to use its value on Index.

AccountController

   public ActionResult YNHHConsentForm(YNHHFormVM model)
    {
        if (result == 0 || isSuccess == false)
        {
            model.FormSubmissionMessage = "Something went wrong please try again";
            return View(model);
        }
        else
        {
            SessionItems.IsAuthorizationFormFilled = true;
            //ViewBag.FormSubmissionMessage="Form submitted successfully";
            ViewData["FormSubmissionMessage"] = "Form submitted successfully";
            return RedirectToAction("Index", "Default");
        }
    }

Index(Default)

   @if (ViewData["FormSubmissionMessage"] !=null)
            {
                <div class="alert alert-success">
                    ViewData["FormSubmissionMessage"].ToString()
                </div>
            }

I am using ViewBag and ViewData for first time so not able to figure out where I am doing wrong.


Solution

  • You need to use TempData. In the YNHHConsentForm() method

    TempData["FormSubmissionMessage"] = "Form submitted successfully";
    return RedirectToAction("Index", "Default");
    

    and access it in the Index() method (and add it to (say) ViewBag so you can then access it in the view.

    ViewBag.MyMessage = TempData["FormSubmissionMessage"];
    

    and in the view

    <div class="alert alert-success">@ViewBag.MyMessage</div>
    

    For an explanation of the difference between ViewData ViewBag and TempData, refer this answer

    Side note: TempData only lasts one redirect so if the user refreshed the browser, the message would not be generated again. You can use .Keep() or .Peek() to solve this if its critical (refer this answer for more detail)