Display data in a 2 column Table
i'm new to asp.net mvc. I'm displaying data from a linq to sql query but unsure how to render a a list of data in a 2 column table.
eg. A list of products. I've seen this example, but wondering if there are any other suggestio开发者_如何学Pythonns - http://haacked.com/archive/2010/05/05/asp-net-mvc-tabular-display-template.aspx.
Hence if i have 6 products returned, i want them displayed in a table in this format, see below.
You could also use div's instead of a table (this is what I would do to be honest), which would make it a LOT cleaner:
<style type="text/css">
.products { width:600px; }
.product { width:280px; margin-right:20px; float:left; height:150px; }
</style>
<div class="products">
<% foreach (var item in Model) { %>
<div class="product">
<%: item.SomeProperty %>
<%: item.AnotherProperty %>
</div>
<% } %>
<div style="clear:left;"></div>
</div>
This isn't the cleanest (definitely ugly to look at)... but you could add a boolean that you toggle so you can alternate between rendering the left and right column when rendering each product. IE:
<table>
<% bool left = true;
foreach (var item in Model) { %>
<%: left ? "<tr>" : "" %>
<td>
<%: item.SomeProperty %>
</td>
<%: !left ? "</tr>" : "" %>
<% left = !left; } %>
<% if (!left) { //need to end the lastrow if we had an odd number of items %>
<td></td>
</tr>
<% } %>
</table>
There is probably a better way to do this, but this is what first comes to mind.
this is what i came up with, it's not the cleanest code, but there doesn't seem to be a clear cut way of doing this.
<table>
<%
int productCount = 0;
foreach (var x in Model)
{
productCount++;
if (productCount % 2 == 1)
{
%>
<tr>
<td>
<%=Html.Encode(x.ProductId)%>
</td>
<%
}
else
{
%>
<td>
<%=Html.Encode(x.ProductId)%>
</td>
</tr>
<% }
}
if (productCount % 2 == 1)
{%>
<td> </td></tr>
<%}%>
</table>
I presume what you are asking is how to write a table without having to write/use a template as in the haacked.com blog post. Its simple. Just type the definition into the view itself. Remember that, in a sense, a view is just a template, that takes your model and spits out html.
Using the haacked.com article, and assuming you have a strongly typed view using a Model that holds the results of your query, lets say, an IEnumerable MyData, just type into your view:
<table>
<tr>
<th>
Column Name 1
</th>
<th>
Column Name 2
</th>
</tr>
<% foreach (var x in Model.MyData) { %>
<tr>
<td>
<%: x.Column1 %>
</td>
<td>
<%: x.Column2 %>
</td>
<% } %>
</tr>
</table>
The above assumes that each object in MyData has two properties, Column1 and Column2. Adapt, style to taste and enjoy.
精彩评论