2

I'm trying to pass a success message from my Controller action to the View. However, any solutions i try or come across googleing doesn't seem to work. After an hour trying to figure out what I'm doing wrong I'll ask here.

In the exampel i use ViewBag but I've tried with TempDate["MyMessage"] = "Some message"; still same.. Value is always null in View...

Controller

    public ActionResult EditSupplier(Supplier supplier)
    {
        try
        {
            if (ModelState.IsValid)
            {
                this._service.Update(supplier);
                ViewBag.UserMessage = "Supplier updated successfully";

            }
        }
        catch (Exception ex)
        {
            ModelState.AddModelError(String.Empty, ex.Message);
            TempData["UserMessage"] = "Error, supplier couldn't be updated";
            return View("Error");
        }
        return RedirectToAction("Supplier", new { id = supplier.SupplierId });
    }

View

@if (ViewBag.UserMessage != null)
{
  <p>@ViewBag.UserMessage.ToString()</p>
}
Rovdjuret
  • 1,458
  • 3
  • 19
  • 40

1 Answers1

1

In the RedirectToAction call you cause the client browser to redirect by sending it a "redirect" status. Your local state is lost as soon as you return that status and end your response - it is not persisted through to the next request. You need another "way" to persist that information, such as redirecting to SupplierEditSuccess, for example, which would be a view that assumes that the edit succeeded, or passing a Success parameter to Supplier which says that the last edit succeeded and to show a message accordingly.

However, within your exception catch, you should be able to see the TempData within the view, so if you deliberately throw an exception after this._service.Update(supplier); then you should be able to access the message in TempData["UserMessage"].

Edit I wrote a lot about passing data between action results in my answer to "storing a js value from 1 ActionResult to use in another ActionResult", and less directly in my answer to "Is ViewBag and ViewData also part of state management in asp.net mvc?" which might help you create a suitable solution for your scenario.

Community
  • 1
  • 1
Andy Brown
  • 18,961
  • 3
  • 52
  • 62
  • @devH, I covered all the different state mechanisms and which apply to different scenarios in [my answer here](http://stackoverflow.com/a/16485025/1945631), which might help you – Andy Brown Nov 11 '13 at 18:14