How to pass an array through in JQuery Ajax and ho

2019-06-10 05:23发布

问题:

I have a problem where i have to pass a list of ids to serverside to delete some users, but my requirement is to do it using JQuery Ajax. But I was not able to get the parameters in my server side can anybody give a help on this to sort out pls?

What i have done till now is shown below

  var idList = new Array();
$(document).ready(function () {
    $('input:checkbox').click(function () {
        //set our checkedcount variable to 0
        var checkedCount = 0;
        //loop through and count the number of "checked" boxes
        $('.acceptUsers:checked').each(function () {
            //if a checked box was found, increase checkedCount by 1
            idList.push($(this).val());
            checkedCount++;
        });
    });
});
      $('#btnDelete').click(function () {
          url = 'Teacher/UpdateUserStatus/';
          var ids = idList.toString();
          $.ajax({
              type: "POST",
              url: url,
              data: { 'userIds': ids },
              contentType: "application/json; charset=utf-8",
              dataType: "html",
              success: function (data) {
                  alert('yeah');
                }
              }
          });
      });

What i have done in my server side is

    [HttpPost]
    public JsonResult UpdateUserStatus(object userIds)
    {
        List<int> usersToDelete = new JavaScriptSerializer().ConvertToType<List<int>>(userIds);
        this.userService.DeleteUsers(usersToDelete);
        return Json(true, JsonRequestBehavior.AllowGet);
    }

Can anybody know why my server side method is not calling?

回答1:

First thing that I have noticed is that you have one curly brace extra inside your code. Try the following one :

 $('#btnDelete').click(function () {
      url = 'Teacher/UpdateUserStatus/';
      var ids = idList.toString();
      $.ajax({
          type: "POST",
          url: url,
          data: { 'userIds': ids },
          contentType: "application/json; charset=utf-8",
          dataType: "html",
          success: function (data) {
              alert('yeah');
          }
      });
  });

If this is not working, start a debug session and put a break-point on the action method and see if you are hitting the server or not.

Also have a look at the following article for an example of JQuery Ajax calls on ASP.NET MVC 3 :

http://www.tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and-asp-net-mvc-partial-views