ASP.NET MVC: How do I pass a list (from a class in Model) to a repeater in a View?

How do I do the above? I've started using MVC and I'm having issues passing data around.

My specific problem is to do with a list of objects I have in my Model which I need to access in a View and iterate through.

Thanks in advance.

Answers


Let's say your controller action looks something like

public ActionResult List()
{
    List<string> myList = database.GetListOfStrings();
    (...)
}

Now you want to pass your list to the view, say "List.aspx". You do this by having the action return a ViewResult (ViewResult is a subclass of ActionResult). You can use the Controller's View method to return a ViewResult like so:

public ActionResult List()
{
    List<string> myList = database.GetListOfStrings();
    (...)
    return View("List", myList);
}

To be able to access the list in a strongly-typed fashion in your view, it must derive from ViewPage, where T is the type of the data you are passing in. Thus, in the current case our view (in List.aspx.cs) would something like this:

public partial class List : ViewPage<string>
{
    (...)
}

The data passed into the view in this way is referred to as the "ViewData". To access the data, you must go through the ViewData.Model properties on the ViewPage. Thus, to render the contents of the list you would write (in List.aspx)

<ul>
    <% foreach(var s in this.ViewData.Model){ %>
    <li> <%= s %> </li>
    <% } %>
</ul>

Here, this.ViewData.Model has the type you specified the type parameter T in ViewPage, so in our case this.ViewData.Model has type List.

You can use a repeater for rendering stuff like this, but I wouldn't recommend it. If you want to use something similar, check out the Grid module of the MvcContrib project on CodePlex.


Need Your Help

Does Filemaker's SQL's GROUP BY support aliases?

filemaker

I'm having trouble with Filemaker's SQL commands.

Could not find member <method name> in Swift (multiple instances)

ios swift compiler-errors

I am trying to build my Xcode project however, I keep getting "Could not find member " build errors in three different instances from the code below. Please help.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.