Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

ViewData and ViewBag

$
0
0

I know this has probably been talked about alot around here, but I'm always confused about this.

So I want to be able to show a message to the users of my app when something has happened or an action is successfull.

I hate nullrefrence exceptions, and I know that ViewData sometimes can throw one if it is used in the view but has no value. Does this mean that in order to use ViewData I always need to set a value for it, like this?

ViewData["Message"] = "Update successfull";<p>@ViewData["Message"]</p>

So in order for me to show an update success message, I need to always populate it to something? This would not work for me, because I want the message to only pop up when relevant and not be a part of the site design(if I always have to populate it, then the message would always display something and take space unnecessarily).

Is ViewData an array of (generic)elements? Because I can make a list<T> and put it in ViewData["Nameoflist"].

Furthermore, I can use viewbag to refrence something set as viewdata. So using ViewBag.Message, get's me the same result in the View as using ViewData["Message"]. What is the difference here? I can only speculate that ViewBag holds ViewData elements. But when to use what? The only thing I know is that if I use ViewBag in the view I don't have to worry about the application throwing a null exception


Viewing all articles
Browse latest Browse all 9386

Trending Articles