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

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
});

Advertisements

May 7, 2013

Pass Hidden Input from View to MVC Controller

Filed under: ASP.NET,C# — Duy Nguyen @ 11:51 am
Tags: , , , , ,

Make sure your input has an id AND name attribute. Having just the id attribute will not work.

<% using (Html.BeginForm("MyAction", "Controller", FormMethod.Post, new { id = "formId", target = "_self" })) 
   { %>
     <input type="hidden" name="myHidden" id="myHidden" value="false" />
<% } %>

Then in the controller, access the form values like this.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyAction(FormCollection form)
{
     string myHiddenInput= form["myHidden"];
}

Create a free website or blog at WordPress.com.