by Michal Rogozinski
27. July 2009 17:52
Pretty common scenario when working with Controllers and Views is passing a data entity (or more than one) to it and than rendering the in the view with that data. In this scenario we’re using a common Data Transfer Object paradigm.
There are multiple ways of passing data to views in ASP.NET MVC. One though is of my interest now.
Traditionally you have the View Data Dictionary, which you can stuff with any objects and then read in the view layer. The drawback here is that you have to explicitly cast each member of View Data Dictionary, since the information about type is being lost.
1: public class HomeController : Controller
2: {
3: public ActionResult Index()
4: {
5: ViewData["Title"] = "Home Page";
6: ViewData["Message"] = "Welcome to ASP.NET MVC!";
7:
8: return View();
9: }
10: }
A view can be strongly typed, so a developer is able to pass an object to it and define what type of object it is. We can specify the model for the view (or should I rather say DTO) via an overload of the View method in the Controller.
1: //
2: // GET: /Note/Create
3: public ActionResult Create()
4: {
5: return View(new Note());
6: }
Behind the scenes this sets the value of ViewData.Model property to value passed into the View method. The next step is to change the type of the view inherit from ViewPage<T>. Since there is no code-behind, it’s best to achieve it this way:
1: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
2: Inherits="System.Web.Mvc.ViewPage<Note>" %>
Moreover, it’s very common to use enumerable types, in this case we’re getting into:
1: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
2: Inherits="System.Web.Mvc.ViewPage<IEnumerable<Note>>" %>
The upper will allow us to manage any IEnumerable collection of Note objects, for example List<Note>.
Finally, to use the Model in our view assuming we passed List<Note>:
1: <ul>
2: <% foreach (Note n in Model) {%>
3: <li><%= Html.Encode(p.Title) %></li>
4: <% } %>
5: </ul>
Strongly typed views give us the the IntelliSense – less error prone guessing and typos, and so convenient.