How do I Generate Divs in ASP.NET MVC?
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
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>
<%} %>
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.
精彩评论