Seemingly simple MVC partial view question
-
18-09-2019 - |
Question
I am trying to display my data (images) in two columns of a table in my partial view. The code below does not seem to work as it displays each image in its own row. What am I missing?
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Import Namespace="ULS_Site.Models"%>
<%var alternating = false;%>
<table>
<% foreach (var item in ViewData.Model as IEnumerable<image>) %>
<%{%>
<%if (!alternating) %>
<%{ %>
<tr>
<%}; %>
<td>
<a href="<%= item.image_path %>" target="_blank" >
<img src="<%= item.image_path %>" alt=" " width="100" />
</a>
</td>
<%if (!alternating) %>
<%{ %>
</tr>
<%}; %>
<%alternating = !alternating;%>
<%}%>
</table>
Solution
<%if (alternating) %>
<%{ %>
</tr>
<%}; %>
EDIT: When closing the tr
, you will need to reverse the condition.
This will not close the tr
till the line alternative = !alternating;
executed.
EDIT2: Also, why are you opening and closing <%=
and %>
on each of the line, when you are still in the code mode?
i.e Isn't there a clean way to write it?
<%if (alternating)
{%>
</tr>
<%}; %>
OTHER TIPS
I recommend a readability-driven approach. In addition to these other soulutions, you can also use list and display each item inside an LI tag to observe the separation of concerns rule a little better. Some standards based CSS and a sprinkle of jQuery can keep the code small and easy to read:
<ul>
<% foreach (var item in ViewData.Model as IEnumerable<image>) { %>
<li>
<a href="<%= item.urlPath %>">
<img src="<%= item.imagePath %>" alt="" /></li>
<% } %>
</ul>
The CSS is can be as simple as this:
ul {
width:200px; /* twice the individual LI width */
}
ul li {
height:60px;
width:100px;
margin:0;
padding:0;
float:left;
list-style-type:none;
}
And now that you've got raw output and structured handled, a little jQuery can take care of your alternate display needs. This will give you two vertical columns:
<script type="text/javascript">
$(function() {
$("li:odd").css("background-color", "#F00");
});
</script>
A slightly different jQuery selector can paint colors on alternate horizontal rows.
Try this, this will solve your problem with rendering two columns per row in the tablee.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Import Namespace="ULS_Site.Models"%>
<%var alternating = true;%>
<table>
<% foreach (var item in ViewData.Model as IEnumerable<image>) %>
<%{%>
<%if (alternating) %>
<%{ %>
<tr>
<%}; %>
<td>
<a href="<%= item.image_path %>" target="_blank" >
<img src="<%= item.image_path %>" alt=" " width="100" />
</a>
</td>
<%if (!alternating) %>
<%{ %>
</tr>
<%}; %>
<%alternating = !alternating;%>
<%}%>
</table>