How to send an array using Url.Action

1.1k views Asked by At

I have an array of integers called data which I would like to send from my View to a specific controller, I could see that i can send integers and strings and it works with the code that I have so far, but when I try to send an array I can get the data correctly.

This is the code that I have in my view, it is something simple just to be in perspective.

function SeeStation() {
                var data = [];
                var i = 0;
                $("input:checkbox:checked").each(function () {
                    data[i] = $(this).val();
                });
                window.location.href = "@Url.Action("ExportData", "Dispatch")?id=" + data;
            }

and this is the code in the controller. I know it doesn't make much sense but so far I am focused on correctly obtaining the array by parameter.

public ActionResult ExportData(int[] id)
        {
            var data = cn.ESTACIONDESPACHOes.ToList();
            return View(data);
        }

In my array data I store something like this [1,2,3] and I would like to get something similar in the controller array id.

4

There are 4 answers

0
Lisander Cuedari On BEST ANSWER

It will not bind like that. To get the id array in your action you need to have the link at the end like this: *Dispatch/ExportData?id=1&id=2&id=3*

Your "@Url.Action("ExportData", "Dispatch")?id=" + data; will not generate that (data will give the numbers separated with commas).

You can just build the query string when you enumerate the checkboxes.

function SeeStation() {
    var data = '';
    $("input:checkbox:checked").each(function () {
    data += 'id='$(this).val() + '&';
    });  
    window.location.href = "@Url.Action("ExportData", "Dispatch")?" + data;
}

You will have a "&" in the end. You can easily remove it, but it will not affect anything.

There may be better ways to do this though, but I just used your function.

0
Akbar Badhusha On

try

@Url.Action("ExportData", "Dispatch", new { id= [1,2,3] })
0
Venkatesan On

Store the Values in the Hidden Fields @Html.HiddenFor(m => m.Ids, new { @Value = [1,2,3] })

Then Using the Ajax Get Method Pass the Hidden fields

In the Controller Method Convert the sting to array using string extension method

1
Raju Jikadra On
function SeeStation() {
            var data = [];
            var i = 0;
            $("input:checkbox:checked").each(function () {
                data[i] = $(this).val();
            });
            location.href = '@Url.Action("ExportData", "Dispatch")?id=' + data;
        }

Please remove window keyword.