ViewData 的替代品?
我对 MVC、ASP.net 以及一般的服务器端脚本编写还很陌生。
我在 www.asp.net/mvc 上观看了一个教程视频,其中有人正在解释模板。他解释说控制器使用viewdata向视图发送信息。
如果我错了,请纠正我,但我相信它是这样使用的:
CONTROLLER: ViewData["PropertyName"] = value;
VIEW: <%= ViewData[ "PropertyName"] %>
这是正确的用法吗?
除了使用 ViewData 之外,还有什么更好的方法呢?它有什么不好呢?
I'm pretty new to MVC, ASP.net, and, well, server-side scripting in general.
I was watching a tutorial video at www.asp.net/mvc where the person was explaining a template. He explained that the controller using viewdata to send information to the view.
Correct me if I'm wrong, but I believe it was used like this:
CONTROLLER: ViewData["PropertyName"] = value;
VIEW: <p><%= ViewData["PropertyName"] %></p>
Is this correct use?
What would be a better way to do it, instead of using ViewData, and what's bad about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在很多视图情况下,我建议使用 ViewData 集合。
在大多数情况下,我会使用强类型视图与单独的每个视图的视图模型。
There are very view situations that I would advocate the use of the ViewData collection for.
For the most part, I would use Strongly Typed Views with individual View Models for each View.
与使用 ViewData 相比,更好的方法是创建一个新的 Model 对象并将其传递给强类型化到 Model 的 View。
模型 (Models/MyModels.cs)
视图 (View/My/Index.aspx)
控制器 (Controllers/MyController.cs)
Html.Encode可以这样使用:
或者如果您是 使用 ASP.NET 4.0
Rather than using the ViewData a better approach would be to create a new Model object and pass that to the View which is strongly typed to the Model.
Model (Models/MyModels.cs)
View (View/My/Index.aspx)
Controller (Controllers/MyController.cs)
Html.Encode can be used like this:
or this if you're using ASP.NET 4.0
Justin 关于 ViewData 使用以及视图模型的使用是正确的(这绝对是最适合您需求的解决方案)。
Session
是另一种选择,但它往往是一个滑坡,但您确实要求替代方案。Justin is correct regarding ViewData usage, as well as using View Models (This is definitely the solution that will probably most fit your needs).
The
Session
is another option, but it can tend to be a slippery slope, but you did ask for alternatives.ViewData 非常适合您不确定需要什么的完全随机数据。
如果您正在构建定义良好的视图,您将需要使用强类型视图。这些让您的视图继承特定的业务对象(或更有用的是 ViewModel)来显示数据。在这种情况下,您可以访问强类型模型成员,即 Model.SomeProperty,而不是 ViewData["SomeProperty"]。
此外,Html.Encode 旨在放置重复用户输入数据的数据元素。它的目的是防止 HTML 注入。
ViewData is good for complete random data that you're not sure what you're going to need.
If you're constructing well-defined views you'll want to use Strongly Typed Views. These let your view inherit from a particular business object (or, more usefully, a ViewModel) to display the data. In this situation, instead of ViewData["SomeProperty"] you could have access to a strongly-typed Model member ie Model.SomeProperty.
Also, Html.Encode is meant to be put around data elements that repeat user-entered data. It is meant to prevent HTML injection.