PoliDev
PoliDev

Reputation: 1458

How to pass List values from Ajax call to controller

I want to pass List values from Ajax call to controller. The values are splitted by commas. But when it is coming to controller, i want it will show like list. but it is showing with commas.

My code here

function Activate() {
    var orderId = "";
    var count = 0;
    $("input:checkbox[name=ActivateOrder]:checked").each(function () {
        if (count == 0) {
            orderId = $(this).val();
        }
        else {
            orderId += "," + $(this).val();
        }
        count = count + 1;
    });

    var data = "orderIds=" + orderId;
    var url = '<%= Url.Action("activate", "Report","Add") %>';

    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "json",
        success: function (data) { 
            if(data.error=="3")
            {
                alert(data.message);
                document.getElementById('checkall').checked=false;
                 window.location = "/Add/Report/savedetails?lstOrderIds=" + orderId;
            }

        }
    });
    return false;

}

I have to pass the lstOrderIds into controller

 public ActionResult savedetails(List<int> lstOrderIds)
{
            //Implement some logic..
}

How to convert this? I tried so many ways. but no hope. I think i am not that much genius to fix this. Help me to find out..

Upvotes: 0

Views: 12953

Answers (1)

Prashant Sarvaiya
Prashant Sarvaiya

Reputation: 354

Create Array like below.

    var selected = new Array();
    $('input:checked').each(function () {
        selected.push($(this).attr('id'));
        alert("Event " + $(this).attr('id') + " will be compared");
    });

    $.ajax({
        url: "/Event/CompareEvents",
        contentType: "application/json",
        type: "POST",
        datatype: "json",
        data: JSON.stringify({eventIds:selected}),
        error: function (xmlHttpRequest, errorText, thrownError) {
            alert(xmlHttpRequest, errorText, thrownError);
        },
        success: function (data) {
            alert("success");
            document.location = data;
        }
    });

Controller Code

   [HttpPost]
   public ActionResult CompareEvents(List<int> eventIds)
{
    return null;
}

Upvotes: 4

Related Questions