新的 ViewModel 并没有废弃 ASP.NET MVC 3 中的 ViewModel 模式,对吗?
根据我的理解,ViewModel 模式旨在将所有相关数据传递给 View,因为 1) 视图不应执行任何数据检索或应用程序逻辑,2) 它支持类型安全、编译时检查和编辑器智能感知。查看模板。
由于动态表达式是在运行时定义的,这是否意味着我们没有得到 2) 的任何好处?
In my understanding, the ViewModel pattern was designed to pass all the relevant data to View because 1) the view shouldn't perform any data retrieval or application logic and 2) it enables type-safety, compile-time checking, and editor intellisense within view templates.
Since dynamic expressions are defined at runtime, does this mean we don't get any of the 2)'s goodies?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不会失去任何现有功能。您仍然可以拥有强类型视图,这样当您访问
Model
属性时,它将属于您指定的类型。唯一添加的是访问 ViewData 字典中的项目的更短方法。而不是以下内容
您可以
注意到,您不会失去任何类型安全,因为您从未真正拥有任何类型安全, 。在前一种情况下,键是一个字符串(不确定它是否存在于字典中),而值是一个对象,因此除非您对其进行强制转换,否则您无法使用它做那么多事情。在后者中,您也得不到智能感知,并且返回的值必须转换为有用的值。
事实上,
View.MyData
的实现只需获取属性名称(“MyData”)并返回来自 ViewData 字典的值。可以说,您失去的一件事是无法在键名中包含空格或其他非合法 C# 标识符的字符。
You do not lose any of the existing functionality. You can still have a strongly-typed view such that when you access the
Model
property it will be of your specified type. The only thing that is added is a shorter way of accessing items in the ViewData dictionary.Instead of the following
you can have
Notice that you do not lose any type-safety because you never really had any. In the former case the key is a string (no certainty that it exists in the dictionary) and the value is an object so unless you cast it you can't do that much with it. In the latter you also get no intellisense and the returned value must be cast to something useful.
In fact the implementation of
View.MyData
simply takes the property name ("MyData") and returns the value coming from the ViewData dictionary.Arguably the one thing you lose is the ability to have spaces or other characters that are not legal C# identifiers in your key names.