0

It's possible to build an array in jquery/javascript to send it to my controller c# ?

I get a list of employes from a select multiple, i can alert them like this :

    <div class="demo">
        <select style="display:none" id="liste" multiple="" placeholder="Select">
            @foreach (var employe in ViewBag.Employes)
            {
            <option value="@employe.ID_Employe">@employe.Name</option>
            }
        </select>
    </div>

    <a class="btn btn-default" id="check" href="#">Suivant</a>

My script :

        $('#check').on('click', function () {
            $("#liste").find("option:selected").each(function () { alert($(this).text()); });
        });

I send data like this :

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: '/MyAjaxRoute',
            data: { arraytosend: arraybuildInJS },
            success: function (response) {
                if (response.success) {
                    alert('yes');
                }
        },
  • Can you explain me how to make an array in js and to receive it in a c# mvc controller ?
3

2 Answers 2

0

First create an Action in your Controller as:

public JsonResult SaveArrayData(List<string> myData)
{
   if(myData.Count == 0) return Json(new {success = false});

   //do something with myData
   return Json(new {success = true});
}

Then in your js code you can do the following:

var array = [];
$('#check').on('click', function () {

$("#liste").find("option:selected").each(function () {
    array.push($(this).text)
});

$.ajax({
     type: 'POST',
     dataType: 'json',
     url: '@Url.Action("SaveArrayData", "MyController")',
     data: { myData: array },
     success: function (response) {
       if (response.success) {
          array = [];//empty the array you can also use array.length = 0
          alert('yes');
       }          
     }
   });
});
Sign up to request clarification or add additional context in comments.

Comments

0

I guess push is what you're looking for.

var arraybuildInJS = [];
$('#check').on('click', function () {
            $("#liste").find("option:selected").each(function () { arraybuildInJS.push($(this).text()); });
        });

Remember you should expect an Enumerable of string in your controller. As you don't code it, try matching the objects.

Comments

Your Answer

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