Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net server side Conditional attribute or unchecked attribute?

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

like image 967
Maslow Avatar asked Aug 09 '26 05:08

Maslow


2 Answers

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) %>
/>
like image 112
Darin Dimitrov Avatar answered Aug 10 '26 19:08

Darin Dimitrov


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 %>"
  />
like image 38
Bob Avatar answered Aug 10 '26 19:08

Bob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!