I have a javascript at the end of my view that creates an array of the selected checkboxes. The button that submits the form allows me to access form collection and other parameters. If I attach a click event to the same button to run the java script, the data in the javascript gets sent but the form collection parameter is null. If I remove the click function from the script, my script model parameter is null and the other parameters are ok.
Here’s how my script data gets to the controller gets.
I’m using a model: namespace SchoolIn.ViewModels { public class EnrollmentOptionsVM {
public virtual string OptionID{ set;get;}
public virtual string UserChoice { set;get;}
}
}
[HttpPost]
public ActionResult Edit(int id, FormCollection formCollection, String[] options, List<EnrollmentOptionsVM> model, String[] instructorString, String[] selectedteacher,string[] selectedCourses, Student student, string course, Enrollment enrolls, Assignment assignment, String[] searchString)
<script type="text/javascript">
var $checkboxes = $('input[type="checkbox"]');
$(document).ready(function () {
var options= [];
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
var item={ "UserChoice" : "checked", "OptionID": "YouCanSetIDHere"};
}
else
{
var item={ "UserChoice" : "unchecked", "OptionID": "YouCanSetIDHere"};
}
options.push(item);
})
$.ajax({ type:
'POST', url: '@Url.Action("Edit","Student")',
contentType: 'application/json',
data: JSON.stringify(options)
}).done(function (html) {
});
alert('success')
});
</script>
And here’s the signature of the Edit Post.
[HttpPost]
public ActionResult Edit(int id, FormCollection formCollection, String[] options, List<EnrollmentOptionsVM> model, String[] instructorString, String[] selectedteacher,string[] selectedCourses, Student student, string course, Enrollment enrolls, Assignment assignment, String[] searchString)
I put an alert() in the script to be sure it runs ok and it does. Why is my model value null if I don’t wrap the script code in a click event?