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 ?
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Aym2ric
  • 31
  • 1
  • 1
  • 6

3 Answers3

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.

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');
       }          
     }
   });
});
Izzy
  • 6,740
  • 7
  • 40
  • 84
0

Thx your for your answers, i can succesfull send my data but i dont find the way to parse it in my c# controller

public ActionResult GetAjaxSession(string searchequipe)
    {
        if (searchequipe != null)
        {
            var equipe_decode = HttpUtility.UrlDecode(searchequipe);

// how to parse my json variable : searchequipe ? 

            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }

        return null;


    }
Aym2ric
  • 31
  • 1
  • 1
  • 6