Input:
Id, PartId, Name
1, 1, Head
1, 2, body
1, 3, Tail
2, 1, Head
2, 2, Leg
Output Display:
- Head, Body, Tail [Delete(1)]
- Head, Leg [Delete(2)]
My Code:
<ol>
<%
int prev = -1;
foreach (var item in t)
{
if(prev != item.ResponseId){
if (prev != -1)
{%>
<%= Html.ActionLink("[replacethis]", "RemoveResponse", new { id = item.ResponseId })
.Replace("[replacethis]", "<img src=\"../../Content/images/delete_icon.gif\" class=\"borderlessImage\" title=\"Remove\"/>")%>
</li>
<%} %>
<li>
<% }
else {
%>, <%
} %>
<%= Html.Encode(item.ResponsePartValue) %>
<% prev = item.ResponseId;
} %>
<%= Html.ActionLink("[replacethis]", "RemoveResponse", new { id = prev })
.Replace("[replacethis]", "<img src=\"../../Content/images/delete_icon.gif\" class=\"borderlessImage\" title=\"Remove\"/>")%>
</li>
</ol>
Questions:
- What are the ways to refactor this?
- Any MVC tricks I am missing?
Well, first of all you could create an
HtmlHelperthat renders image links for you, instead of generating the anchor tags first and then replacing their content with an image.Take a look at here.
Also you don’t have to use
<%=every time you need to ouput some text. If you already have opening code blocks (ie<%), then you can just useResponse.Writemethod to output what you want. In cases like yours, that’ll most likely look better than%> <%=.Though, I admit I don’t exactly know what you are listing here and how you want it to display. But following your algorithm, I guess this is what I would have done :