views:

50

answers:

2

Is it a good idea to move checkbox-checking logic out of the markup, specifically the 'checked="checked"' inline script such as

<input type="checkbox" name="LikesWork" <%= Model.LikesWork ? "checked=\"checked\"" : "" %> />

and have this be replaced with a some code that takes a dictionary with a javascript (jQuery) selector as the key and a bool as the value. Then the checkboxes would get checked by the javascript, simplifying the markup.

<input type="checkbox" name="LikesWork" />

...

<%
Dictionary<string, bool> checkElements = new Dictionary<string, bool>();
checkElements.Add("#likesWork", Model.Account.LikesWork);
Response.Write(Html.CheckCheckboxes(checkElements));    
%>

If this isn't a good idea, why not?

+2  A: 

I disagree with that approach. If you don't have to, I wouldn't rely on javascript for that. It may not be likely, but there are several reasons why that could fail:

  • User has JS disabled
  • Another js error on the page prevents your script from processing
  • User is accessing your site from a mobile device of sorts that doesn't support your script

HTML is just safe. In my opinion, this introduces a potential point of failure that didn't exist before.

Jage
+2  A: 

You could always just use the strongly typed CheckBoxFor helper and avoid this mess altogether. Relevant bit from documentation:

Return Value
Type: System.Web.Mvc.MvcHtmlString An HTML input element whose type attribute is set to "checkbox" for each property in the object that is represented by the specified expression.

R0MANARMY