I had this question I was looking for the answer and I saw this question’s answer
What's the difference between ViewData and ViewBag?
which in the answer many people mentioned using neither ViewBag or ViewData is “safe”. I did not understand why since I’m new to web applications and the whole concept of it and also to MVC overall. So my questions are:
- Why is ViewBag and ViewData not a safe way to pass data?
- What is the best way to pass data? (The most important question)
I really appreciate your help!
The alternative is a strongly typed model object. Some people prefer this because it prevents some of the runtime exceptions that can occur when working with the dynamic ViewBag object. It also allows useful IDE features like autocompletion and tends to lead to more readable code.
There is a good blog post from Microsoft’s Rick Anderson that describes and gives examples of the different options, which you may find useful.
If the strongly typed option looks like something you’d like to pursue, this tutorial may be useful: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/accessing-your-models-data-from-a-controller