I have an action called Messages which has two forms.
The first form posts to SendMessage and the second posts to MessagesDelete. Both pages return a ReturnToAction of the Messages view, and both use TempData to return feedback data (message sent, messages deleted etc) indicating that an action has occured.
MessagesDelete works fine, returning the TempData just the first time and then removing it in future requests. SendMessage on the other hand, persists the TempData endlessly.
Here’s some simplified code.
[Authorize]
public ActionResult Messages(int? id, string message)
{
MessagesModel model = new MessagesModel();
// build model data here
return View(model);
}
[Authorize]
[HttpPost]
public ActionResult MessagesDelete(int[] selectedObjects, int? id)
{
// delete objects
TempData["MessagesDeleted"] = selectedObjects.Count() + " deleted";
return RedirectToAction("Messages", new { id = id });
}
[Authorize]
[HttpPost]
public ActionResult SendMessage(SendMessageModel model)
{
// send my message
TempData["MessageSent"] = "message sent!";
return RedirectToAction(model.action, new { id = model.action_id } );
}
The only difference I can see is that MessagesDelete is send the id directly, whereas SendMessage has it as a property within the model.
It looks like you’re trying to implement one-off messages to users based on actions they take. In this situation, I would rathe architect your solution a little bit differently than take on the headache that is using
TempDataand it’s unreliability.Here’s what I would do:
1) Create a base ViewModel for all ViewModels expecting to show one-off messages.
2) Then, add a OnResultExecutingFilter to pull data from session to store in the view model (or, add an override to your base controller):
3) Then, you simply need to assign to that session variable, and you can be assured that the next view (and not partial view) will assign the one off message to the view model, and then the data will be deleted.