到底什么是强类型 在 Asp.Net MVC 中查看数据

发布于 2024-08-20 04:45:56 字数 64 浏览 5 评论 0原文

Asp.Net MVC 中的“强类型视图数据”是什么意思?

谢谢

What is meant by "strongly typed view data" in Asp.Net MVC ?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

罪歌 2024-08-27 04:45:56

ASP.NET MVC 中的强类型视图继承自 System.Web.Mvc.ViewPage 并包含由 T 指定类型的 Model 属性。这允许智能感知在您的视图中工作。

A strongly typed view in ASP.NET MVC inherits from System.Web.Mvc.ViewPage<T> and contains a Model property that is of type specified by T. This allows intellisense to work in your views.

撩起发的微风 2024-08-27 04:45:56

每个视图都有一个Model 属性。对 View 进行强类型化意味着使其继承自某个 ViewPage,并且 Model 属性变为 T 类型。如果您的视图不强类型化,则 Model 类型为 "目的”。

对视图模型进行强类型化的优点是可以直接访问模型的属性。您可以获得智能感知和编译器检查,而不是依赖使用“魔术字符串”来访问 ViewData 字典 - 如果您的模型发生更改,这会在运行时中断。

例如,如果您

public class Person
{
   public int Age { get; set; }
}

Person 类上设置了强类型视图,那么您将能够从视图模板访问 Model.Age。如果您的视图不是强类型的,那么 Model 将没有可供您访问的属性,并且您必须将其显式转换为类型或通过 ViewData 字典传递数据。

要强类型化此视图,只需使其继承自 ViewPage 即可。

Every View has a Model property. To strongly type a View means to make it inherit from some ViewPage<T>, and the Model property becomes the type of T. If you don't strongly type your view, the Model is of type "Object".

Strongly typing your View's model has advantages in that you can directly access the properties of the Model. You get intellisense and compiler checking, instead of relying on using "magic strings" to access a ViewData dictionary - which would break at runtime if your model ever changed.

For example, if you had

public class Person
{
   public int Age { get; set; }
}

and you made your View strongly typed on the Person class, you would be able to access Model.Age from your view templates. If your View was not strongly typed, then Model would have no properties for you to access, and you would have to explicitly cast it to a type or pass your data through a ViewData dictionary.

To strongly type this view, you simply make it inherit from ViewPage<Person>.

落叶缤纷 2024-08-27 04:45:56

假设您需要在视图上显示几条松散相关的数据:联系信息、销售预测和通话历史记录。您可以简单地将它们注入 ViewData 并将它们拉出并从视图中强类型化它们,但是更好的方法是创建一个封装每个这些的自定义模型。然后,您可以将视图本身强类型化到该自定义模型中。它可以发挥类型安全性,并使代码辅助更加直观,并具有其他优点(例如可测试性)。

Let's say you have a need to display several pieces of loosely related data on a View: Contact Information, Sales Forecasts and Call History. You could simply just inject these into the ViewData and pull them out and strongly type them from the View, however a better approach would be to create a custom Model which encapsulates each of these. Then you would strongly type the View itself to this custom model. It plays into type safety and makes code-assist more intuitive amongst other benefits such as testability.

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