0

I want to pass data from my cshtml file to my Controller. I want to pass an array. So I m build this code:

js:

function nextFunction() {
        var listaDomande = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.pagina.domande));
        var arrayRisposte = [];
        //mi devo ricostruire il numero di domande che c'è in pagina, per ogni tipo devo verificarne i valori
        for (i = 0; i < listaDomande.length; i++) {
            var dom = listaDomande[i];
            //alert(dom.idTipoDomanda);
            if (dom.idTipoDomanda == 6) {
                //DOMANDA CON OPTION BUTTON
                //devo verificare per questo tipo di domande, quante opzioni erano possibili
                //e recuperare solo il valore della opzione selezionata
                for (n = 0; n < dom.opzioniDomanda.length; n++) {
                    //verifico quale è l'opzione selezionata dall'utente
                    var opzioniDomanda = dom.opzioniDomanda[n];
                    if (document.getElementById("oDomanda" + opzioniDomanda.ordinalId).checked) {
                        var value = document.getElementById("oDomanda" + opzioniDomanda.ordinalId).value;
                        alert(value);
                        var risposta = {
                            idDomanda: dom.rowId,
                            valore: value
                        };
                        arrayRisposte[i] = risposta;
                        break;
                    }
                }
            } else if (dom.idTipoDomanda == 3) {
                //TEXT BOX
            }
        }


        var valueText = document.getElementById("tDomanda");
        alert(listaDomande.length);

        $.ajax({
            url: '/Questionario/nextPage',
            data: JSON.stringify({ risposta: arrayRisposte}),
            type: "GET",
            success: function (data) {
                //TODO: Add whatever if you want to pass a notification back
                alert("RR Salvato");
            },
            error: function (error) {
                //TODO: Add some code here for error handling or notifications
                alert("Si è verificato un errore");
            }
        });
    }

this is my controller method:

[HttpGet]
        public void nextPage(RisposteUtente[] risposta)
        {
            try
            {
                Console.WriteLine("");

            }
            catch (Exception e)
            {
                Console.Write("");
            }
        }

This is my RispostaUtente object

public class RisposteUtente
    {
        public int idDomanda { set; get; }
        public String valore { set; get; }

        public RisposteUtente()
        {

        }
    }

now if I try to execute js function, the call comes to the controller, but RisposteUtente[] is null.

1

Modify your AJAX call like this:

    $.ajax({
        url: '@Url.Action("nextPage", "Questionario")',
        data: { "json": JSON.stringify(arrayRisposte)},
        type: "GET",
        success: function (data) {
            //TODO: Add whatever if you want to pass a notification back
            alert("RR Salvato");
        },
        error: function (error) {
            //TODO: Add some code here for error handling or notifications
            alert("Si è verificato un errore");
        }
    });

And your Controller method will look like:

using System.Web.Script.Serialization;
//using Newtonsoft.Json

[HttpGet]
public void nextPage(string json)
{
  try
  {
    var serializer = new JavaScriptSerializer();
    dynamic jsondata = serializer.Deserialize(json, typeof(object));

    //Deserialize your JSON string if the struccture is an array
    //var deserializedjson=JsonConvert.DeserializeObject<List<RisposteUtente>>(json);


    //Get your variables here from AJAX call if the string is not an array
    var idDomanda = jsondata["idDomanda"];
    var valore =jsondata["valore"];

    //Do something with your variables here 
    Console.WriteLine("");

  }
  catch (Exception e)
  {
    Console.Write("");
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.