TBA
TBA

Reputation: 1197

How to pass a JavaScript Array to ASP.Net MVC Action as part of post

I have a cshtml as follow,

DoPost.cshtml

@using (Html.BeginForm("Purchase", "PurchaseOrder", FormMethod.Post, new { @id = "frmPurchase" }))
{

// statements

// statements

<input type="button" id="submitPurchase" onclick = "myPurchase()" value="Select" />
}

In Javascript I have an array strings in variable "ExtraItems"

ExtraItems[0] ="123"
ExtraItems[1] ="124"
ExtraItems[2] ="125"

My Action which accept the data is as follows,

public ActionResult Purchase(PurchaseOrderModel model)
        {            
            //Do some stuff with the passed data
            return View("Purchase", model);
        }

In the above PurchaseOrderModel, I have the property

public string[] SelectedProducts { get; set; }

to accept the Javascript Array elements.

What I tried: The simple post did not work as the JavaScript array elements are not part of the Form elements,I couldn't use a @Html.HiddenFor because it is an array.

Hence tried to do an Ajax post under function myPurchase(),

$a.post('@Url.Action("Purchase", "PurchaseOrder")', { SelectedProducts: ExtraItems });

Here I did not get the ExtraItems details under model.SelectedProducts in the action. The biggest issue was i wanted to load the Purchase.cshtml View from the action, instead I got the controll back to the Jquery Post.

Please help me how can I solve this.

Upvotes: 0

Views: 5345

Answers (4)

nraina
nraina

Reputation: 354

Take a string property in your model and then send the data as comma separated string

var dataToSent = ExtraItems.join(',')

If you have a property named Datum of type string in your model Purchase then the data to be sent will be, passing model

data : 'Datum=' + dataToSent

In your action you can split data into array also for return response you have to redirect the page in the success function of your ajax call

$.ajax( {
        type: 'POST',
        url: '/Default1/Index',
        data: { SelectedProducts: ExtraItems },

        traditional: true,
        success: function ( response )
        {
            window.location.href = "/controller/action" <--your url


        }
    } );

Upvotes: 1

ARUNRAJ
ARUNRAJ

Reputation: 489

Here is my example for solving your issue
-----------------------------------------
//Script
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<script>
    var ExtraItems = ["aa","bb","cc","ff"];
    function a()
    {
        $.ajax( {
            type: 'POST',
            url: '/Default1/Index',
            data: { SelectedProducts: ExtraItems },

            traditional: true,
            success: function ( response )
            {
                alert( 'Sucs' );


            }
        } );
    }

</script>
<button onclick="a();">click</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>

//Controller

 [HttpPost]
        public ActionResult Index( string[] SelectedProducts )
        {
              return View();
        }

Upvotes: 2

NicoD
NicoD

Reputation: 1189

You should post your javascript array as a json object. You use the JSON.stringify() method converts a value to JSON. Something like :

 $.ajax({
        url: '@Url.Action("Purchase", "PurchaseOrder")',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ 
            SelectedProducts: ExtraItems
        })
    });

Upvotes: 3

anssi
anssi

Reputation: 739

Use $.ajax function with the option traditional:true for enabling ASP.NET MVC default model binding for the list of string items.

Upvotes: 1

Related Questions