0

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?

4

2 回答 2

0

If your script is in the head tag then when you reference the checkboxes var $checkboxes = $('input[type="checkbox"]'); they aren't in the page yet so $checkboxes will be an empty jQuery object

You need to put the $checkboxes = $('input[type="checkbox"]'); inside the $(document).ready function

于 2013-03-30T21:28:04.267 回答
0

Ok I see what’s happening. Although my Javascript and the Razor post to the same action, their parameters won’t be sent at the same time in same post. To solve this I created a different action and used the click function to trigger the event.

于 2013-03-31T07:16:18.837 回答