3

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.)

2 Answers 2

3

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) %>
/>
Sign up to request clarification or add additional context in comments.

2 Comments

ah. how simple, I feel that was quite obvious.
Shouldn't your helper method take a DateTime? I'd guess that CompletedDate is a DateTime? not a bool?
3

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 %>"
  />

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.