Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Massive list to View in MVC3

New to ASP.NET MVC (using MVC3 with Razor now) and I'm confused on passing an object from the Controller to the View. Specifically, I'm experimenting with MVC3 and Rob Conery's interesting Massive (http://blog.wekeroad.com/helpy-stuff/and-i-shall-call-it-massive). I'm messing with a blog as a simple web application to experiment with.

HomeController.cs:

public ActionResult Index()
        {
            var table = new DynamicModel("mydb", tableName: "Posts");
            //grab all the posts
            var posts = table.All();
            ViewData["Posts"] = posts;

            return View();
        }

This part works great. But how do I do this?

return View(posts);

If I reference @posts.PostID in the View, it errors out and says it's not valid. So I tried creating a strongly typed view against the DynamicModel, but posts still wasn't there.

I know I can create a ViewModel and type the view against that and plug my data in there. This is more about understanding how the Controller/View interact.

Thanks!

like image 441
Nathan Loding Avatar asked Mar 30 '11 10:03

Nathan Loding


2 Answers

First of all you need to create a class. For example:

public class Post : DynamicModel
{
    public Post(): base("db")
    {
       PrimaryKeyField = "PostID";
    }

}

In the Controller you can have :

public ActionResult Index()
        {
            var table = new Post();
            var posts = table.All();

            return View(posts);
        }

So you can create a Strongly Typed View and set the Model of the View to IEnumerable. The View will be like this :

@model IEnumerable<dynamic>

<h2>Index</h2>
<ul>
@foreach (var item in Model)
{
    <li>@item.PostID</li>
}
</ul>
like image 65
GeoChatz Avatar answered Oct 23 '22 02:10

GeoChatz


ASP NET MVC Templates is the solution.

First of all, using ViewData is discouraged especially now in MVC 2.0 and 3.0 where there are many better ways to pass state to the view.

Strongly typed view is the way to go. But What if you have a collection to pass? Well, you still can create a strongly typed view for the collection (or generic list) but standard solution is to use ASP NET MVC templates (which are ascx files) for the item and not the collection and call RenderPartial on your parent view:

For example:

        <div>
            <% for (int i = 0; i < Model.Bars.Count; i++)
               {%>
            <h3>
                <a href="#">Bar
                    <%: String.Format("{0:g}", Model.Bars[i].DocumentDate.ToShortDateString())%></a></h3>
            <div>
                <%: Html.DisplayFor(m => m.Bars[i].Content)%>
            </div>
            <%}%>
        </div>

There is a very good series on this topic here.

like image 25
Aliostad Avatar answered Oct 23 '22 04:10

Aliostad