balanv
balanv

Reputation: 10898

How to use Collection in .net MVC 3?

I am new to .net MVC 3. I am trying to render a collection. How do I map a collection to a model and and operate on it.

I am searching for a simple example of how to do this. If anyone has come across any examples of doing this, can you please send them to me so I can learn.

Thanks

Upvotes: 0

Views: 497

Answers (1)

Jeremy Seekamp
Jeremy Seekamp

Reputation: 2796

Here is a great example of how to iterate a collection in MVC 3

http://weblogs.asp.net/scottgu/archive/2010/10/19/asp-net-mvc-3-new-model-directive-support-in-razor.aspx

Specifically you want to follow this pattern:

Controller

public class NamesController : Controller
{
    public ActionResult Index()
    {
        var names = new List<string>() { "Bob", "James", "Jim" };

        return View(names);
    }
}

View

@model IList<string>

<!DOCTYPE html>

<html>
    <head>
    </head>
    <body>
        <h1>Names</h1>

        <ul>
            @foreach(var name in model) {
                <li>@name</li>
            }
        </ul>
    </body>
</html>

Upvotes: 3

Related Questions