Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strongly-typed view vs dynamic-typed view

Tags:

asp.net-mvc

I start to use ASP .NET MVC. And, as I can see, there are 2 approaches 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?

like image 388
Pavel Surmenok Avatar asked Feb 10 '11 10:02

Pavel Surmenok


2 Answers

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.

like image 122
amurra Avatar answered Sep 26 '22 00:09

amurra


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.

like image 21
mayank Avatar answered Sep 26 '22 00:09

mayank