ASP.NET MVC 强类型视图与否?
最佳实践是什么 - 仅使用不带任何参数的强类型视图,通过 ViewData 字典传递,或者在视图中使用类似的内容也是一个不错的主意:
<%: (string)ViewData["helloMessage"]%>
谢谢。
What is the best practice - to use only strongly typed views without any parameters, that passes through the ViewData dictionary, or it's a not bad idea to use something like this in a view:
<%: (string)ViewData["helloMessage"]%>
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该更喜欢强类型视图。在某些情况下,您只需要一个字符串(如示例中所示),该字符串不属于模型,那么可以使用它。另一种方法是将这个变量封装成一个类并将该类传递给视图。结果将是一个强类型视图:-)
我个人不喜欢神奇的字符串。
You should prefer strongly typed views. In some cases you need only one string like in your example, which doesn't belong to a model, then it is OK to use it. The other way is to encapsulate this variable into a class and pass the class to the view. The result would be a strongly typed view :-)
I personally don't like magical strings.
使用“魔力字符串”并没有什么错
但它们很容易出现打字错误。
在 MVC 3 中,控制器中有一个动态对象
ViewModel
,它对应于视图中的 View 对象。因此,您可以在控制器中分配
ViewModel.MyData="something";
并在视图中将其用作@View.MyData
这是一种更好的方法。
仅拥有强类型视图会受益于编译时检查。
这由你决定。
我个人使用动态对象。
There is nothing wrong with using "magic strings"
But they are subject to typing errors.
In MVC 3 there is a dynamic object
ViewModel
in controller wich corresponds to a View object in view.So you can assign
ViewModel.MyData="something";
in controller and use it in your view as@View.MyData
It is kinda a better way to go.
Having only strongly typed views benefits from compile time checking.
And it is up to you to decide.
Personally I use dynamic object.