开发者

Pass Massive list to View in MVC3

开发者 https://www.devze.com 2023-02-20 14:13 出处:网络
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 (

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.

HomeCont开发者_运维技巧roller.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!


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>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号