Should ViewData Never Be Used?

I tried to check out the best practices for using asp.net mvc, and many say that we should never use ViewData. I read this post and it looks like this.

One of the reasons I can think of using ViewData is that you want to pass only one value to the view. But for more than one value, it seems better to use ViewModels. But if they are included as part of the structure, then they should have some advantages and benefits.

When should ViewData be used? What are the best practices that should be followed when using ViewData so that it is not used incorrectly?

+3
source share
5 answers

I prefer to use strongly typed view models from the start. I very much prefer the absence of "magic strings" at the same time.

There is never one rule for all situations, but usually this is the first approach that I use.

+3
source

Quote from Scot Gu (source link: nerddinnerbook )

The use of line-based dictionaries, as typos can lead to errors that will not be caught at compile time. non-printable dictionary ViewData requires the use of an "like" operator or casting when using a strongly typed language like C # in a presentation template.

0
source

ViewPages ModelView ASP.NET MVC.

ViewData ViewPage, ViewModels, :

  • IntellySence.
  • Html
0

ViewData, . - , , , , , , ViewModel, ViewData.

, const .

public abstract partial class BaseController : Controller
{
    public const string MessagesViewDataKey = "Base.Messages";

    protected override void OnActionExecuted(ActionExecutedContext filterContext) {
        if (filterContext != null && filterContext.Controller != null && !filterContext.IsChildAction) {
            filterContext.Controller.ViewData[MessagesViewDataKey] = Messenger.MessageQueues;
        }

        base.OnActionExecuted(filterContext);
    }
}

// site.master
<% if (ViewData[BaseController.MessagesViewDataKey] != null)
           Html.RenderPartial("DisplayTemplates/MessageList", ViewData[BaseController.MessagesViewDataKey]); %>
0

I do not like to use them, but I found them useful in a situation where I want to display some message to the user on all pages. For example, I have a user control that displays messages to the user. It is also present on my main page. It checks ViewData["messages"]and TempData["messages"]And if one of them is not null, it displays the messages present. If they are both equal to zero, it is not.

This allows me to save all my models from inheritance based on the base class with the Messages attribute and gives me more flexibility.

0
source

Source: https://habr.com/ru/post/1785551/


All Articles