开发者

Strongly-typed view vs dynamic-typed view

开发者 https://www.devze.com 2023-02-09 12:30 出处:网络
I start to use ASP .NET MVC. And, as I can see, there are 2 approac开发者_开发问答hes to pass data to view:

I start to use ASP .NET MVC. And, as I can see, there are 2 approac开发者_开发问答hes to pass data to view:

  1. Make View that inherits ViewPage and pass dynamic object to the view.
  2. Make strongly-typed View, that inherits ViewPage, and pass an instance of custom view-model class to the view.

What are pros and cons of each one?


Always use a strongly type views whenever possible so that you know exactly what data is being passed as the Model to that View. If you use dynamic you really don't always know what the data will be and could lead to runtime errors if things change.


According to JOSH DOOLAN, Strongly-Typed views are more useful for handle Complex Type data. For example, I have the a class of a person:

Public Class Person

{
 String _name;
 String _age;
 Pet _pet;

 // gets & sets below..etc
 }

If in the event you have a use case where you wanted to bind this particular class to a form (to create a “New” person), it would be pretty straight forward up until you got to the complex type Pet.

What you would do is simply strongly type the person to a particular view and then within that view call a template or view file that is strongly typed to “Pet”. To assign a complex type to a template/view you simply utilise the html mvc helpers Html.ControlFor. In this particular instance because you are not dealing with a simple html control like a text box you would use the:

Html.EditorFor(model => model.Pet, "Pet")  

Here you can see, you are putting an instance of the view model “pet” into the strongly typed view called “Pet” in order to get back a completely data filled view model when the original view form is submitted.

This is a very powerful way to simplify and encapsulate data in more complex and larger scale web sites.

0

精彩评论

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