0

In my requirement, all views should be able to display notifications based on what happened within Actions in the controllers. The implementation as it stands is in a BaseModel which is inherited by all Models needing to show notifications. Then, any view with this requirement simply calls:

@{ Html.RenderPartial("MessageCtrl", Model); }

And a notification is rendered. This works fine in cases where an Action is returning a view directly, and is usually handled like this in an Action:

model.SetMessage(response);
return View(model);

...where SetMessage updates the notification related properties of the model from an object returned from my service. All responses implemented an interface I created called IResponse, so messaging can be handled throughout.

The problem arrises when I need to return a View from a different Action and still show a notification.

For example, on my EditUser action, if edit was successful, I want to show the Index view. To achieve this from the EditUser action, I need to return RedirectToAction (because simply returning the view will return the correct view with the incorrect URL indicating it is EditUser when it is not). However, RedirectToAction loses all notion of my model and BaseModel, so by the time it redirects, it has lost my notification. I know I can use RouteValues, but that defeats the purpose of having a common base model driven notification approach. I even looked at the ViewBag (usually I dismiss it as the ugly part of MVC), but found that ViewBags only persist for the life time of a single request, and using RedirectToAction, the ViewBag is empty again by the time it hits the target Action. Another thought was to store it in a session object, but that sounds downright ugly to me.

This seems like its a pretty standard requirement. Is there a standardised approach to passing common data (like notifications) around to different views asside from through the querystring through a RedirectToAction?

1 Answer 1

1

I think you are looking for TempData which only persists data in session across one redirect.

Sign up to request clarification or add additional context in comments.

4 Comments

Great Scott! That sounds great!
To keep your code looking clean and DRY, you can override OnActionExecuting and check if TempData has your message and assign it to the property on your model that way.
That sounds like a great idea. I'll have a play with it.
I used OnActionExecuted instead, and also after grabbing the message out of TempData I had to clear TempData as it was persisting it. Aside from that, worked like a charm!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.