2

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:

  1. Why is ViewBag and ViewData not a safe way to pass data?
  2. What is the best way to pass data? (The most important question)

I really appreciate your help!

Community
  • 1
  • 1
Amin
  • 578
  • 1
  • 6
  • 18

2 Answers2

1

There have been debates. I always use specific View Models.

You can use ViewBag or ViewData too but not preferred.

ViewData is not safe because,

ViewData["foo"] might not be set in the controller but you try to access it so you ll fail. Thus ViewBag was introduced which uses Dynamic features of language.

So ViewData is somewhat safer. However, as a good design creating View Model Object per view is ideal.

DarthVader
  • 52,984
  • 76
  • 209
  • 300
  • If ViewBag and ViewData is not preferred, then what is better than this? I'm asking since that is the only way I know of passing data. – Amin Nov 23 '12 at 06:39
  • 1
    I wrote it View Model per View. You create a class per view, which will contain the entities on the page. – DarthVader Nov 23 '12 at 06:39
1

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

rouan
  • 5,339
  • 6
  • 22
  • 36