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

2
  • Possible duplicate. Check this stackoverflow.com/questions/25288240/… Commented Apr 1, 2016 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. Commented Apr 1, 2016 at 18:20

2 Answers 2

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(',');
Sign up to request clarification or add additional context in comments.

Comments

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.