1

I have an MVC Action which accepts a list of values as shown below:

 [HttpGet]
        public JsonResult Events(string[] vals)
        {
            var events = _lcmEventsRepository.FindAllByEventTypeId(vals[0]);

            return Json(events);
        }

How to send some values to this Action from javascript?

I'm using the below code but the value which is received at the server side is not in the right format:

var eventtypes = ['1', '2'];

 $.ajax({
                url: shouldRepopulateFromAction,
                //data: { vals: JSON.stringify(selectedValues) },
                data: { vals: JSON.stringify(eventtypes) },
                type: 'GET',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    alert(data);
                },
                error: function (data) {
                    alert('error!');
                }
            });

vals parameter has one member with the value of

["1","2"]
2
  • 1
    Have you tried with traditional: true, parameter? and don't use JSON.stringify Commented Feb 12, 2014 at 9:22
  • nice, t hanks :) - what's the non-traditional way? Commented Feb 12, 2014 at 9:27

1 Answer 1

1

What you are trying to do with the JSON.stringify(), serializing the array, is taken care of if you set 'traditional: true'. What this does is sending the array like this:

/Events?vals=1&vals=2

if you don't set 'traditional: true' the array will be sent like this:

/Events?vals%5B%5D=1&vals%5B%5D=2   

So the solution is this:

 var eventtypes = ['1', '2'];

 $.ajax({
                url: shouldRepopulateFromAction,
                data: { vals: eventtypes },
                type: 'GET',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                traditional: true,
                success: function (data) {
                    alert(data);
                },
                error: function (data) {
                    alert('error!');
                }
            });

You should consider using POST when sending arrays to the server.

Sign up to request clarification or add additional context in comments.

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.