views:

43

answers:

1

I'm pretty new to ASP.Net MVC. I've created a model that fills a List<> with multiple custom objects called "Result". Then, in my controller, I get this List and put it into the ViewData.

I am at a bit of a loss as to how to utilize this List in my view (aspx page). My first try was just to put ViewData["Results"] between the <% %>, but clearly this is not working, and I suspect I need to cast it somehow and also reference my original definition of the Result custom object. However, the aspx page does not really seem set-up for this type of coding...and there is no code-behind, and I've heard I'm supposed to keep the view "dumb". Most of the examples I've seen don't seem to cover this scenario of passing custom objects, just simple strings, etc.

Can this be done elegantly using just the <% %> syntax? Do I need to create a code-behind page and handle it there? If so, how would one be created, as they are not provided by default.

+1  A: 

To make the view integrate seamlessly with the object you're passing to it from the action, you need to change the Inherits= attribute in the @Page directive located at the top of the view.

Make sure you pass this object to the view from the action, via the following:

public MyController : Controller 
{
     public ActionResult ShowResults()
     {
          List<Result> results = GenerateResults();
          return View(results); // this passes 'results' as the model of the view
     }
}

In this case, you have a custom object called Result which you pass a list of to the view. So in the @Page directive you change the Inherits= to

Inherits="System.Web.Mvc.ViewPage<List<MyNameSpace.Models.Result>>"

So your full @Page directive will look something like this:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<MyNameSpace.Models.Result>>" %>

What this does is tell the View that your Model is of type List<MyNameSpace.Models.Result>.

Now, in the view, the Model object will be automatically cast to type List<MyNameSpace.Models.Result> so you can do the following seamlessly and cleanly.

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<MyNameSpace.Models.Result>>" %>

<table>
   <tr>
      <th>Result PropertyOne</th>
      <th>Result PropertyTwo</th>
   </tr>

<% foreach(var result in Model){ %>

   <tr>
      <td><%: result.PropertyOne  %></td>
      <td><%: result.PropertyTwo  %></td>
   </tr>

<% } %>

</table>
Baddie