Strongly Typed Views in MVC

When you add a new View in MVC, you get an opportunity to create it strongly typed. In the image given below, when you check ‘Create a strongly-typed view’ and select the ‘Model class’ you get following code snippet on the view page.

@model MvcApplication2_InternetTemplate.Models.Comment

Above peace of code is just a fully qualified name of the model, now we need to supply the type name to get intellisense on view page.

@model IEnumerable<MvcApplication2_InternetTemplate.Models.Comment>

And now, try iterating over model ‘Comment’, you will have intellisense support (aka Strong Typed View Page).

Here is the controller that passes the model instance to the view page:

public ActionResult Index()
    var comments = new List<Comment>();

    comments.Add(new Comment {
        Id = 1,
        Name = "Deepak",
        Post = "Good post my friend."
    comments.Add(new Comment {
        Id = 1,
        Name = "Abhimanyu",
        Post = "Hey, you are doing great."

    return View(comments);

Alternatively on view page to avoid needing to specify a fully qualified type name for the model, we can use @using declarations.

One more better approach when working on really large application declare the
namespace in the web.config file within the Views directory, but this will not guarantee you the intellisense.

Now, suppose controller returning model via view data dictionary (aka ViewBag), as one given below.

Now to to deal with ViewBag; on the view page we can iterate and display the comment, you will notice intellisense here too.

You can notice we cast ViewBag.Comments to an IEnumerable<> interface. We can also use dynamic keyword but it will lost the benefits of intellisense.

Now, you can clearly see how difficult it is to keep the code clean with intellisense feature and this is where strongly typed views come in.

Hope this helps. Thank You.


Popular posts from this blog

Lambda two tables and three tables inner join code samples