asp.net-mvc 什么是 ASP.NET MVC 中的强类型视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2896544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:20:01  来源:igfitidea点击:

What is strongly-typed View in ASP.NET MVC

asp.net-mvcview

提问by Fraz Sundal

What is strongly-typed View in ASP.NET MVC?

什么是 ASP.NET MVC 中的强类型视图?

采纳答案by Darin Dimitrov

It is an aspx page that derives from System.Web.Mvc.ViewPage<TModel>. It is said that this view is strongly typed to the type TModel. As a consequence to this there's a Modelproperty inside this view which is of type TModeland allows you to directly access properties of the model like this:

它是一个源自System.Web.Mvc.ViewPage<TModel>. 据说这个视图被强类型化为 type TModel。因此,此视图中有一个Model属性,它的类型TModel允许您直接访问模型的属性,如下所示:

<%= Model.Name %>
<%= Model.Age %>

where as if your aspx page derived from System.Web.Mvc.ViewPageyou would need to pull values from ViewDatathe view no longer knows about the TModeltype:

好像从System.Web.Mvc.ViewPage您派生的 aspx 页面需要从ViewData视图中提取值不再知道TModel类型:

<%= (string)ViewData["Name"] %>
<%= (int)ViewData["Age"] %>

or even worse:

甚至更糟:

<%= ((SomeModelType)ViewData["model"]).Name %>

and there's no compile time safety in such code.

并且在这样的代码中没有编译时安全性。

Notice also that there's the ViewUserControl<TModel>counterpart for strongly typed partials (ASCX).

另请注意ViewUserControl<TModel>,强类型部分 (ASCX)有对应的部分。

回答by jco

Strongly typed views are used for rendering specific types of model objects, instead of using the general ViewData structure. By specifying the type of data, you get access to IntelliSense for the model class.

强类型视图用于渲染特定类型的模型对象,而不是使用通用的 ViewData 结构。通过指定数据类型,您可以访问模型类的 IntelliSense。

回答by David M

It's a view which specifies the type of the object passed to it as its model - so instead of a view that inherits from ViewPage, it inherits from ViewPage<T>where Tis the type of the model.

它是一个视图,它将传递给它的对象的类型指定为它的模型 - 因此它不是从ViewPage继承的视图,而是从ViewPage<T>where继承T模型的类型。