0

Suppose I have some javascript like in the image. In the array I put the (multiple) values in the variable array and send this array to an action method in a controller. However, in the action method I will get this as an 'object'. How do I get the values out of this 'object'? I prefer to not use an ajax post. Is this possible? If yes, how do I 'catch' the values in the action method?

enter image description here

John Doe
  • 259
  • 1
  • 6
  • 18
  • Possible duplicate. Check this http://stackoverflow.com/questions/25288240/ajax-post-multiple-data-to-asp-net-mvc – John Newman Apr 01 '16 at 18:07
  • Are you saying you want to post data back, but not using AJAX, just a submit button for instance? If you have a model, one of it's properties could be your int array. – Andy Wiesendanger Apr 01 '16 at 18:20

2 Answers2

1

You should use the data property to send the array of integers

var array = [1, 2, 4];    
$.ajax({
    url: '/Home/Items',
    type: 'POST',
    data:  { items: array },
    success: function(data) {
        console.log(data);
    }
});

Assuming your have an action method like this to receive it

[HttpPost]
public ActionResult Items(int[] items)
{
    // to do  : do something with items
    return Json(items);
}

Now i see you read the value of an input field and use that as the value of your array variable. I am not sure what format of value you have in your input field. If it is comma seperated list of int (Ex : "1,3,5"), you may use the split function to get an array from that.

 var v = "2,5,78,8";
 var array = v.split(',');
Shyju
  • 214,206
  • 104
  • 411
  • 497
0

In Ajax call:

    var items = ['USA', 'UK', 'Canada'];
    $.ajax(
        {
            type: "POST",
            url: "/Test/Details",
            contentType: 'application/json',
            data: JSON.stringify({ function_param: items })
        });

In Controller:

    public ActionResult Details(string[] function_param)

If you don't want to use Ajax call, then create an input type hidden control in html and put the javascript array to the hidden field and submit the form and get value in controller by using request.form["hiddencontrol"]

In JS:

    $("#hiddenControl").val(JSON.stringify(items));
Nabin
  • 163
  • 1
  • 12