views:

68

answers:

2

So I'm just getting started on a simple blog like application written in ASP.NET MVC. Basically I have my CSS made and I'm using jquery for some effects but I'd like to do something like a for each loop to display all the data in my posts array seperated into their own little sections. The CSS already has the style for the divs so its just a matter of creating a dynamic amount on the page.

EDIT: Sorry I didn't mention it, two things though:

1) I've never written an ASP.NET MVC based app only pieces of code for classic ASP.Net

2) To clarify what I'm asking I mean when the person loads the page all the divs will already be generated, I'm not adding more after it loads. Like I said, its to render the main view of a blog, all the posts would be retrieve from the model I'm just trying to figure out how to render it in the view.

Thanks

A: 

On the server, its business as usual, using RenderPartial and looping your posts collection. On the client, using jquery simply call.

var $newDiv = $("<div />");

and append it to the location in your dom that you require.

$newDiv.append(document.body);

Also heres a cool templating engine by the maker of jquery, not sure if thats what you require? Click here Id recommend changing the tag context to something like <# #> instead of johns <% %> which would conflict with asp.nets built in one.

almog.ori
@Ori i think he is looking for the server side one
Pandiya Chendur
Then he should simply use RenderPartial and loop the model collection.
almog.ori
A: 

Assuming that you are passing an IEnumerable of Posts to the view in the ViewModel, you would use something similar to the code given below.

<%foreach (var post in Model) {%>
<div class="post">
    <h2>
        <%=post.Title %></h2>
    <p>
        <%=post.Body %>
    </p>
    <p>
        <%= post.Author%>
    </p>
</div>
<%} %>
Khaja Minhajuddin
Thanks, right before I came here I realized there must be a way to run code inside the view ant <% %> is it. Thank again.
edude05
A better way would be to represent your post as a partial view and use RenderPartial in the loop. see http://vinbrown.blogspot.com/2009/03/using-renderpartial-to-recursively.html
almog.ori
You could definitely use partials in here, but I think for simple situations rendering a block using partials is overkill. However, this would me more appealing when used with the `DisplayTemplates` functionality from asp.net mvc 2. Moreover, beginners need to understand the basic way of rendering content before they look into the advanced stuff.
Khaja Minhajuddin