user1250264 February 2016

How to add success message after HttpPost submits database changes

I have an HttpPost method that add to the database

public ActionResult SubmitData(MyViewModel model)
{
    if (ModelState.IsValid)
    {
        var result = submitData(command);

        if (response.success)   
        {
            return RedirectToAction("MyHttpGetMethod");
        }
    }

    return View("MyHttpGetMethod", model);
}

public ActionResult MyHttpGetMethod(int Id)
{
    MyModel model = GetData(Id);

    return View(model);
}

After the HttpPost is called and the database changes are made successfully, I redirect to the HttpGet action to get the current data after the changes. I like to display a success message on the View. I can't use ViewBag because of the Redirect and I can't use TempData, because it's not recommended here.

Answers


Shyju February 2016

TempData is a valid solution for this specific use case. But if you do not prefer to do that, you can pass a querystring value to indicate the status of the transaction from your HttpPost action to the GET action.

So update your GET action to have another paramter

public ActionResult MyHttpGetMethod(int Id,string m="")
{
    MyModel model = GetData(Id);
    if(!String.IsNullOrEmpty(m) && m=="s")
    {
      // do some code to show the success message here.
      ViewBag.Msg="Saved Successfully";
    }
    return View(model);
}

and in your view, use the ViewBag item to show the message (with whatever styles you want)

<p>@ViewBag.Msg</p>

and in your HttpPost action,

return RedirectToAction("MyHttpGetMethod", new { id =model.Id, m="s"} );

Post Status

Asked in February 2016
Viewed 1,918 times
Voted 5
Answered 1 times

Search




Leave an answer