I have seen a lot of people say that using Viewdata
or ViewBag
is not a good practice for this matter(displaying messages from the controller) because of security reasons. Everyone seems to suggest ModelState
My question is what is wrong with using viewdata to display error messages? If we arent supposed to use ViewData
then what should we use it for?
Asked
Active
Viewed 109 times
0
-
Does this answer your question? [MVC 5 ViewBag security](https://stackoverflow.com/questions/27976615/mvc-5-viewbag-security) – derloopkat Jan 22 '21 at 19:03
1 Answers
0
As @shenku answered before, ViewData
and ModelState
reference the exact same thing, if you look at the code for System.Web.Mvc.Controller
class you will see the implementation for ModelState is:
public ModelStateDictionary ModelState
{
get
{
return this.ViewData.ModelState;
}
}
and @JimmiTh said,
although the main use of ModelState
from an "end developer"'s perspective is in the controller, ViewData
is used as a container for all data that's communicated between the controller and the view. Which is why it also needs to include ModelState
- because, although you'd rarely use it directly in the view, ModelState
is where e.g. many of the HtmlHelper
methods actually get the values from by default when rendering the view from a POST action - rather than Model.

Michael Wang
- 3,782
- 1
- 5
- 15