开发者

ASP.NET MVC 3.0 - Why strong-typing Model in a View, if static compilation is not happening?

开发者 https://www.devze.com 2023-03-10 23:33 出处:网络
I\'m actively developing desktop applications, local and network services, some classic ASP.NET, etc., so I\'m used to static compilation and static code analysis. Now that I\'m (finally) learning ASP

I'm actively developing desktop applications, local and network services, some classic ASP.NET, etc., so I'm used to static compilation and static code analysis. Now that I'm (finally) learning ASP.NET MVC 3.0 I'm seeing that many of the ASP.NET MVC experts and experienced developers are recommending using strongly-typed views in ASP.NET MVC 3.0 (where applicable).

I'm guessing that "strongly-typed" means writing @model=... at the top of a view's code. But in doing that I only get IntelliSense to work, no static code checking is taking place. I can write anything I want in the @model statement in cshtml and it would compile and run. Consequentially, Model.Anything also compiles. In fact, if I don't type @model I can dynamically use whatever model I want that has "compatible" properties and methods.

I'm used to "strongly-typed" meaning "won't compile", like LINQ to whatever just will not compile if you don't get the properties right. Is there any other purpose for @model other than IntelliSense and a run-time error, and why i开发者_C百科s it called strong-typed if it's in fact, not?

Strong typing, Meanings in computer literature


Views are compiled at runtime by default. You can modify your project file (csproj) to compile the views when the application builds by setting the following property:

<MvcBuildViews>true</MvcBuildViews>

Downside of this approach is that your buildtime will increase significantly. You should consider only setting this option to true for release builds.

You can edit your project file by unloading the project, right-click the project and choose Edit ProjectFile


It is possible to setup your project so that it includes views in your compilation. This would be where static typing is useful. Another place would be in runtime, if you try to pass in a model that does not match the expected model you will immediately get an exception. If you were to type views dynamically then you would not know your model was invalid until your view tried to access a property of the model and finds out it isn't there.

The second scenario is also a nightmare if you pass in the wrong model object but it happens to have the same named property as the expected model. Then you just get invalid data and debugging becomes hell.


model is new dynamic type in .net 4.0, so these types get resolved at runtime not at compilation time.

0

精彩评论

暂无评论...
验证码 换一张
取 消