ASP.NET MVC 强类型视图与否?

发布于 2024-10-05 16:28:46 字数 156 浏览 0 评论 0原文

最佳实践是什么 - 仅使用不带任何参数的强类型视图,通过 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 技术交流群。

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

发布评论

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

评论(2

日裸衫吸 2024-10-12 16:28:46

您应该更喜欢强类型视图。在某些情况下,您只需要一个字符串(如示例中所示),该字符串不属于模型,那么可以使用它。另一种方法是将这个变量封装成一个类并将该类传递给视图。结果将是一个强类型视图:-)

我个人不喜欢神奇的字符串。

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.

近箐 2024-10-12 16:28:46

使用“魔力字符串”并没有什么错
但它们很容易出现打字错误。

在 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.

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