简体   繁体   English

从控制器发送数据到视图的最安全和最干净的方法是什么?

[英]What is the safest and cleanest way to send data from controller to view?

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? ViewData 和 ViewBag 有什么区别?

which in the answer many people mentioned using neither ViewBag or ViewData is "safe".许多人在回答中提到既不使用 ViewBag 也不使用 ViewData 是“安全的”。 I did not understand why since I'm new to web applications and the whole concept of it and also to MVC overall.我不明白为什么,因为我对 Web 应用程序和它的整个概念以及整个 MVC 都不熟悉。 So my questions are:所以我的问题是:

  1. Why is ViewBag and ViewData not a safe way to pass data?为什么 ViewBag 和 ViewData 不是一种安全的数据传递方式?
  2. What is the best way to pass data?传递数据的最佳方式是什么? (The most important question) (最重要的问题)

I really appreciate your help!我真的很感谢你的帮助!

There have been debates.有过争论。 I always use specific View Models.我总是使用特定的视图模型。

You can use ViewBag or ViewData too but not preferred.您也可以使用 ViewBag 或 ViewData,但不是首选。

ViewData is not safe because, ViewData 不安全,因为,

ViewData["foo"] might not be set in the controller but you try to access it so you ll fail. ViewData["foo"]可能没有在控制器中设置,但你试图访问它所以你会失败。 Thus ViewBag was introduced which uses Dynamic features of language.因此引入了使用语言动态特性的ViewBag

So ViewData is somewhat safer.所以 ViewData 更安全一些。 However, as a good design creating View Model Object per view is ideal.然而,作为一个好的设计,每个视图创建视图模型对象是理想的。

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.有些人更喜欢这样,因为它可以防止在使用动态 ViewBag 对象时可能发生的一些运行时异常。 It also allows useful IDE features like autocompletion and tends to lead to more readable code.它还允许使用自动完成等有用的 IDE 功能,并有助于生成更具可读性的代码。

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. Microsoft 的 Rick Anderson有一篇很好的博客文章,描述并给出了不同选项的示例,您可能会发现这些选项很有用。

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如果强类型选项看起来像你想要追求的东西,本教程可能会有用: http : //www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/accessing -your-models-data-from-a-controller

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM