Skip massive list for viewing in MVC3

New to ASP.NET MVC (now using MVC3 with Razor), and I'm confused about passing an object from a controller to a view. In particular, I am experimenting with MVC3 and Rob Conery interesting Massive (http://blog.wekeroad.com/helpy-stuff/and-i-shall-call-it-massive). I use the blog as a simple web application for experimentation.

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 refer to @posts.PostID in the view, it throws an error and says that it is invalid. So I tried to create a strongly typed view against DynamicModel, but there were still no posts .

I know that I can create a ViewModel and print a view against this and connect my data there. This is more about how to interact Controller / View.

Thanks!

+6
c # asp.net-mvc asp.net-mvc-3
source share
2 answers

ASP NET MVC templates are a solution.

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

A strongly typed view is the way to go. But what if you have a collection? Well, you can still create a strongly typed view for the collection (or general list), but the standard solution is to use ASP NET MVC templates (which are ascx files) for the element, not the collection and the RenderPartial call in your parent view: / p>

For instance:

  <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> 

This section is a very good series.

+2
source share

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

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

In the controller you can:

 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 view model to IEnumerable. The view will look like this:

 @model IEnumerable<dynamic> <h2>Index</h2> <ul> @foreach (var item in Model) { <li>@item.PostID</li> } </ul> 
+10
source share

All Articles