C# controller function receive an array

Asked

Viewed 86 times

0

I need to take a select array and send it to a function in the controller, but it always arrives as null, even sending the full array. Below is the code: Controller:

[AcceptVerbs(HttpVerbs.Get)]
    public ActionResult GetLocais(int [] idcTipoLocal)
    {
        var local = context.Locais.Where(x => x.IdcSite == ContextSession.UsuarioLogado.IdcSite && x.Status /*&& x.IdcTipoLocal == idcTipoLocal*/).Distinct()
               .Select(x => new { id = x.IdcLocal, text = x.Nome }).OrderBy(y => y.text).ToList();
        return Json(local, JsonRequestBehavior.AllowGet);
    }

Javascript:

 var opt = new Array();
$("#selTipLocal").change(function () {
    var obj = [];
    $('#selTipLocal > option:selected').each(
        function (i) {
            opt[i] = $(this).val();
            opt[i] = parseInt(opt[i]);
        });

    var jsonKey = {
        "idcTipoLocal": opt
    };
    $.get("/relocorrencia/getlocais", jsonKey, function (data) {
        $("#selLocal").multiselect("destroy");
        multiSelectRelOco("selLocal", data);
    });
});

I already checked and the arrey arrives ok, but when sending to the controller, idctipolocal always arrives as null

  • Shouldn’t be $.get("/relocorrencia/getlocais", JSON.stringify(opt), function (data) {?

  • I changed and keep coming null

  • How’s the requisition coming along?

  • Tries var opt = [];

  • Try to make a var teste = Request["nomeVariavel"];. Another solution would be to change the parameter int [] idcTipoLocal for string idcTipoLocal and add a parse inside the controler that way: int[] tipoLocalArr = idcTipoLocal.Split(',').Select(int.Parse).ToArray();

1 answer

0

I got it here that way:

var opt = new Array();

$("#selTipLocal").change(function () {

    $('#selTipLocal > option:selected').each(
        function (i) {
            opt[i] = $(this).val();
            opt[i] = parseInt(opt[i]);
        }
    )
    if (opt[0] != null) {
        var obj = [];
        $.ajax({
            cache: false,
            traditional: true,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            type: "GET",
            data: { "idcTipoLocal": opt },
            url: "/relocorrencia/getlocais",
            success: function (data) {
                $.each(data, function (i, obj) {
                    $("#selLocal").multiselect("destroy");
                    multiSelectRelOco("selLocal", data);
                });
            }
        });
    }
    else {
        multiSelectRelOco("selLocal", null);
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.