a developer's notes – a semi-technical web development BLOG

March 8, 2014

Checkbox returning “true,false” from FormCollection.

Filed under: ASP.NET MVC — Duy Nguyen @ 10:46 am
Tags: , , , , , , , , , ,

If you try Request.Form[“checkbox0”], you’ll get the value “true,false” .

Just check this:

form[key].Contains("true"); //some said chrome returns "on"

Or

You could simplify your code doing this:

var strArray = collection["YourCheckboxName"];
char[] delimiterChars = {‘,’};
string[] checkedvalue = strArray.Split(delimiterChars);
var returnValue = checkedValue.Length > 1;

If the checkbox is checked, then the array will contain 2 values, if not, only one.

January 29, 2014

Dynamically added checkbox not posting value to Action Method in controller

I noticed that @Html.CheckboxFor(model => model.MyCheckBox) creates a hidden input with the same name as the actual checkbox. So when you dynamically add a checkbox, make sure you also add in a hidden input with the same name attribute.


var chkboxDiv = $(document.createElement('div')).attr({
	id: 'dynamicChkBoxdiv_'
});

chkboxDiv.html(
	'<input ' +
		'class="myChkBx"' +
		'type="checkbox"' +
		'value=""' +
		'data-val-required="The Active field is required."' +
		'data-val="true"' +
		'name="myChkBxName"/>' +
	'<input ' +
		'type="hidden"' +
		'value=""' +
		'name="myChkBxName"/>' +
);

You also need to add a click event handler to update the hidden value so when the form is submitted, the controller will get the correct ‘checked’ value.

Notice the second parameter that specifies a css class. When you add your dynamic controls, add a css class so you can specify which elements should get the click event delegate. All of your dynamically added controls that have the css class, will now have the same click event.

$("#dynamicChkBoxdiv_").parent().on("click", '.myChkBx', function (e) {
	var name = e.target.name;
	var checkVal = e.target.checked;
	$("input[name^='" + name + "']").val(checkVal); //this will update both the checkbox and hidden input's value
});

Blog at WordPress.com.