永远不应该使用 ViewData 吗?

发布于 2024-10-12 10:05:15 字数 349 浏览 10 评论 0原文

我尝试检查使用 asp.net mvc 的最佳实践,很多人说我们永远不应该使用 ViewData。我已阅读这篇帖子,看来喜欢从那开始。

我可以想到使用 ViewData 的原因之一是,如果您只想将一个值传递给视图。但是对于多个值,似乎最好使用 ViewModel。但如果它们被纳入框架的一部分,那么它们应该有一些优点和好处。

什么情况下我应该使用 ViewData ?使用 ViewData 时应遵循哪些最佳实践,以免被滥用?

I have tried to check the best practices for using asp.net mvc and quite a few say that we should never use ViewData. I have read this post and it seems like it from that.

One reason that I can think of using ViewData is if you are looking to pass just one value to the view.But for more than one values it seems that it would better to use ViewModels. But if they are being included as a part of framework then they should have some advantages and benefits.

What are the cases when I should use ViewData ? What are the best practices to be followed when using ViewData so that it is not misused ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一个人的旅程 2024-10-19 10:05:15

我更喜欢从一开始就使用强类型视图模型。
我更喜欢这样做,这样就不会出现“神奇的字符串”。

从来没有一个规则适用于所有情况,但这通常是我采取的第一种方法。

I prefer to use strongly typed view models from the outset.
I much prefer the lack of "magic strings" by doing this.

Never one rule for all situations but this is usually the first approach I take.

や三分注定 2024-10-19 10:05:15

引用 Scot Gu 的话(来源链接:nerddinnerbook

使用基于字符串的字典,因为
拼写错误可能会导致不会出现的错误
在编译时被捕获。这
也有非类型化的 ViewData 字典
需要使用“as”运算符或
使用强类型时进行强制转换
视图模板中的语言如 C#。

Quote from Scot Gu (link to source: nerddinnerbook)

Using string-based dictionaries, since
typos, can lead to errors that will not
be caught at compile-time. The
un-typed ViewData dictionary also
requires using the "as" operator or
casting when using a strongly-typed
language like C# in a view template.

七颜 2024-10-19 10:05:15

将强类型 ViewPages 与强类型 Model 或 ModelView 结合使用是 ASP.NET MVC 的完美实践。

您可以使用 ViewData 将其他数据传输到 ViewPage,但我更喜欢 ViewModel,因为:

  1. 编译时错误与运行时错误
  2. IntellySence 支持
  3. 轻松重构
  4. 无魔法字符串
  5. 使用数据绑定构建表单的 Html 帮助程序

Usage of a strongly typed ViewPages in couple with a strongly typed Model or ModelView is a perfect practice of the ASP.NET MVC.

You can use ViewData to transfer additional data to ViewPage but I preffer ViewModels because:

  1. Compile time errors vs runtime errors
  2. IntellySence support
  3. Easy refactoring
  4. No magic strings
  5. Html helper to construct form with data bindings
束缚m 2024-10-19 10:05:15

我不喜欢使用它们,但我发现它们在我想在所有页面上向用户显示某种消息的情况下很有用。例如,我有一个向用户显示消息的用户控件。它也出现在我的主页中。它检查 ViewData["messages"]TempData["messages"] 如果其中之一不为空,则显示存在的消息。如果它们都为空,则不会。

这使我能够使所有模型不必从具有 Messages 属性的基类继承,并为我提供了更大的灵活性。

I don't like using them, but I've found them useful in a situation where I want to display some kind of message to the user on all pages. For example I have a user control that displays messages to the user. It is also present in my master page. It checks ViewData["messages"] and TempData["messages"] And if one of those is not null it displays the messages that are present. If they are both null it doesn't.

This allows me to keep all of my models from having to inherit from a base class that has a Messages property and gives me more flexibility.

机场等船 2024-10-19 10:05:15

当我需要通过某些基本控制器或过滤器将数据附加到当前请求时,我经常发现自己使用 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]); %>

I often find myself using ViewData when I need to append data to the current request by way of some base controller or filter. Commonly, master pages will have dynamic content which must be retrieved from the server, and rather than modifying the model returned by the view, or wrapping every model returned in a parent ViewModel, I can simply place the additional data in ViewData.

In order to avoid using strings in my views, I'll often place a const field in a controller class or similar and call the field within the View.

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]); %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文