SomeAnonymousPerson SomeAnonymousPerson - 4 months ago 8
Ajax Question

Pass a list from ajax function to controller

Im trying to pass a list and a string to the controller. When I debug I can see all the information is well taken by the function. The problem is that the list of users the controller recieves is empty.

Here is the JS function:

$(function () {
$("#datepicker").datepicker({
//defaultDate: "+1w",
changeMonth: true,
changeYear: true,
numberOfMonths: 1,
minDate: "01/01/2008"
});
$("button.action").click(function () {
var date = $('#datepicker').val().toString();
var selected_values = new Array();
$(document).ready(function () {
selected_values = []; // initialize empty array
$(".checked:checked").each(function () {
selected_value.push($(this).val());
});
});
$.ajax('EmployeeDate', {
data: {
lstUserName: selected_values,
strDate: date
},
success: function (data, textStatus, jqXHR) {
$('#DataUser').html(data);
},
error: function () {
console.log("error handler when ajax request fails... ");
},

});
});
});


And here is the action:

public IEnumerable<DateTime> getInfoByDate(string strDate, string lstUserName)
{
CareDB context = new CareDB();

SqlParameter Date = new SqlParameter("@Date", strDate);
SqlParameter userName = new SqlParameter("@EmployeeName", lstUserName);

object[] parameters = new object[] { Date, userName };

IEnumerable<DateTime> lst = context.ReleaseDate.SqlQuery("_UserInformationByDate @Date, @EmployeeName", parameters).ToList();

context.Dispose();
context = null;
return lst;
}


Any suggestions? Thanks!

Answer

You are passing your selected_values which is an array, but your method's parameter is a string only. Change to

In the backend you can change the method's parameter to receive an array of strings.

public IEnumerable<DateTime> getInfoByDate(string strDate, string[] lstUserName)
{
    CareDB context = new CareDB();

    SqlParameter Date = new SqlParameter("@Date", strDate);
    SqlParameter userName = new SqlParameter("@EmployeeName", lstUserName);

    object[] parameters = new object[] { Date, userName };

    IEnumerable<DateTime> lst = context.ReleaseDate.SqlQuery("_UserInformationByDate @Date, @EmployeeName", parameters).ToList();

    context.Dispose();
    context = null;
    return lst;
}

Or in the frontend you can change your data

data: {
         lstUserName: selected_values.join(' '),
         strDate: date  },

Edited:

$.ajax('EmployeeDate', {
              data: {
                  lstUserName: selected_values,
                  strDate: date
              },
              dataType: 'json',
              success: function (data, textStatus, jqXHR) {
                  $('#DataUser').html(data);
              },
              error: function () {
                  console.log("error handler when ajax request fails... ");
              },

          });