views:

31

answers:

2

I have the following aspx code:

  <% foreach (ModelDefect modelDefect in GetCodes())
  {%>
<tr>
    <td><input disabled="disabled" name="<%= modelDefect.Code %>" value="<%= modelDefect.Code %>" type="checkbox" checked="<%=modelDefect.CompletedDate.HasValue? "checked":string.Empty %>" /></td>
    <td><a href="javascript:submitForm('<%= modelDefect.DefectId %>');"><%= modelDefect.Code %></a></td>   
    <td><%= modelDefect.Description %></td><td><%= modelDefect.AddedDate %></td>
</tr>
<% } %>

I want the check box to be checked if there is a completed date, and unchecked if not. W3 doesn't appear to say how to leave it unchecked but include the attribute. I don't see a way to conditionally include that attribute on the item. I found a page that suggests that checked="yes" or checked="no" should work but it hasn't. I'd like a browser-independent and standards based solution or... a clean way to conditionally add that tag server side on my asp that is Ajax friendly? (Response.Write doesn't work in Asp.net AJax as I understand it.)

+3  A: 

Write a helper method which can be unit tested and reused:

public static string GetCheckedAttribute(DateTime? value)
{
    return value.HasValue ? "checked=\"checked\"" : string.Empty;
}

and call it in your page:

<input disabled="disabled" 
       name="<%= modelDefect.Code %>" 
       value="<%= modelDefect.Code %>" 
       type="checkbox" 
       <%= GetCheckedAttribute(modelDefect.CompletedDate) %>
/>
Darin Dimitrov
ah. how simple, I feel that was quite obvious.
Maslow
Shouldn't your helper method take a `DateTime?` I'd guess that CompletedDate is a `DateTime?` not a `bool?`
Bob
@Bob, good point. I've updated my answer.
Darin Dimitrov
+3  A: 

Take the attribute and put it as a part of the conditional output, this should work for you

 <input disabled="disabled" 
        name="<%= modelDefect.Code %>" 
        value="<%= modelDefect.Code %>" 
        type="checkbox" 
        <%=modelDefect.CompletedDate.HasValue? "checked=checked":string.Empty %>"
  />
Bob
another simple solution, I plead being sick as the reason I failed to come up with either of these. Also my VS2008 is confusing me with the entire `<% %>` block showing up in red as if there was an unclosed `"` somewhere when there's not.
Maslow