Oleg Sh
Oleg Sh

Reputation: 9013

Pass array to Controller Action via AJAX

I saw similar questions, but none helps me. I have the simplest code:

    public JsonResult JsonGetStatesInfo(object[] instructions)
    {
        if (Request.IsAjaxRequest())
        {

            return Json(String.Empty);
        }
        else
            throw new NoAjaxRequestException();
    }

and client side:

            var instructions = [];
            instructions.push('abc');
            instructions.push('ddd');
            instructions.push('assdbc');
            var inst = JSON.stringify(instructions);
            $.ajax({
                cache: false,
                data: { 'instructions': inst },
                traditional: true,
                dataType: 'json',
                url: '/State/JsonGetStatesInfo',
                type: 'post',
                success: function (resp) {
                },
                error: function (data) {
                    alert(data.error);
                }
            });

On client side I tried with JSON.stringify, without JSON.stringify, with traditional: true, without traditional: true

On server side I tried as parameter : object[], object, List< object >, List< string >, IEnumerable< string > etc

Nothing worked! How to do it correctly?

SOLVED: My problem was trivial - one from real values of array had HTML Tag. Just need add [ValidateInput(false)] to action method

Upvotes: 5

Views: 10242

Answers (4)

Ramin Bateni
Ramin Bateni

Reputation: 17415

You just need the following settings:

Pass array of string to a MVC Action by Ajax:

Controller:

public JsonResult MyAction(string[] instructions)
{
    // Your codes
}

View:

$.ajax({
       data: { 'instructions': ['abc', 'dcs', 'arr'] }, // << Without JSON.stringify 
       traditional: true,  // << Important line
       url: '/State/MyAction',
       type: 'post',
       dataType: 'json',
       success: function (resp) {
            // Your codes
       }
});

Using contentType: "application/json; charset=utf-8" is recommended too.


Pass array of int to a MVC Action by Ajax:

Also I use bellow codes to path an array of int to an Action

Controller:

public JsonResult MyAction(int[] instructions)
{
    // Your codes
}

View:

$.ajax({
       data: { 'instructions': [1, 2, 3] }, // << Without JSON.stringify 
       traditional: true,  // << Important line
       url: '/State/MyAction',
       type: 'get',
       dataType: 'json',
       success: function (resp) {
            // Your codes
       }
});

Upvotes: 4

Sria Pathre
Sria Pathre

Reputation: 182

public ActionResult JsonGetStatesInfo(string[] instructions)
{
   return new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet,
            Data = new { result = instructions.Length}
        };
}

Client side

 var instructions = ['abc', 'dcs', 'arr'];
 $.post('/State/JsonGetStatesInfo', { instructions: instructions },
      function (data) {
       if (data.result!= null && data.result!= undefined) {
        alert(data.result);
    }
});

Try this...

Upvotes: 2

Koby Douek
Koby Douek

Reputation: 16675

Try adding:

contentType: "application/json; charset=utf-8"

To you AJAX call, And please delete the:

JSON.stringify(instructions);

Because you are trying to stringify an object, which will be sent to the server as a string rather than an object (and the server side expects an object).

you can also delete the

traditional: true,
ache: false,

Upvotes: 0

Michel Amorosa
Michel Amorosa

Reputation: 495

At least, you can pass javascript array as a string and deserialize it in the controller

public JsonResult JsonGetStatesInfo(string instructions)

var instructionsArray= JsonConvert.DeserializeObject<string[]>(instructions);

Or use new Array like explained here : https://stackoverflow.com/a/310136/3063094

Upvotes: 1

Related Questions