Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

asp.net core - Displaying error messages from Controller in View

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?

question from:https://stackoverflow.com/questions/65851163/displaying-error-messages-from-controller-in-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...