0

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
  • You should pretty much never use javascript inline. So taking inline code out is a very very good idea. Commented Jul 2, 2010 at 20:20
  • That's inline ASP not javascript. The Html.CheckCheckboxes returns javascript though Commented Jul 2, 2010 at 20:23

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.