Strongly typed view in ASP.NET MVC

When passing the model to MVC you have a couple of options.

Option 1: Passing un-typed model to the view

public ActionResult Product(string id)
{
    var product = new Product();
    product.ID = id;
    product.Name = "iPhone";
    ViewData["product"] = product;
}

In your view you have to cast the value in ViewData to the correct type as follows:

<%
    var item = (Product)ViewData["product"];
%>
<div>
    ID: <%= item.ID %>
    Name: <%= item.Name %>
</div>

Option 2: Pass a strongly typed model to the view

// ViewData["product"] = product;
ViewData.Model = product;

The Page directive of your view must specify the type it expects as follows:

<%@ Page Title="blah" ... Inherits="System.Web.Mvc.ViewPage<Product>" %>

Sometimes you may need to pass more than one object to the view. You can handle this by creating a new class that encapsulates all objects you need and pass an instance of that class to the view instead.


1 Response

RE: Strongly typed view in ASP.NET MVC

Hello my friend! I want to say that this post is amazing, great written and include approximately all significant infos. I would like to look more posts like this .

- cialis   (http://saudesexualhomem.com/1-aumentarpenis.html)   May 12, 2017 08:44 PM

Leave a Reply

Please enter all required information

*

*

*