5

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

Thanks

3 Answers 3

3

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.

0
2

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>.

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.