How to pass Object type parameter to Jsonresult

Asked

Viewed 194 times

2

The view always receives the Null object, why ? This is the jquery code snippet:

var obj = new Object();
obj.TBCOMPOSICAOID = 0;
obj.DSCOMPOSICAO = "TESTE";
var TBComposicao = JSON.stringify(obj);

$.getJSON("/Composicao/Novo/", { pComposicao: TBComposicao}, function(data){
  var url = "/Composicao/List";
  window.location.href = url;

}).fail(function (jqxhr, textStatus, error) {
  var err = textStatus + ", " + error;
  alert('erro: ' + err.toString());                                    
});

This is the method called by getJson:

inserir a descrição da imagem aqui


By the time pass the parameters by String met me, from now on I have to pass these parameters by object, because the form is an employee registration / Addresses:

Model Tbfuncionario

public class TBFuncionario
    {
        public int TBFUNCIONARIOID { get; set; }
        public string MATRICULA { get; set; }
        [DisplayFormat(ApplyFormatInEditMode=true, DataFormatString="{0:dd/MM/yyyy}")]
        public DateTime? DTADMISSAO { get; set; }
        public string NMFUNCIONARIO { get; set; }
        public bool STATUS { get; set; }        
        public string CPF { get; set; }
        public virtual ICollection<TBEndereco> TBEndereco { get; set; }
    }

Model Tbendereco

public class TBEndereco
    {
        [Key]
        public int TBENDERECOID { get; set; }

        public int TBFUNCIONARIOID { get; set; }
        public string LOGRADOURO { get; set; }
        public string NUMLOGRADOURO { get; set; }
        public string COMPLEMENTO { get; set; }
        public string BAIRRO { get; set; }
        public string CEP { get; set; }
        [ForeignKey("TBFUNCIONARIOID")]
        public virtual TBFuncionario TBFuncionario { get; set; }
    }

Javascript snippet that generates the populated object of Employee/Addresses:

//ENVIA DADOS VIA AJAX                
                var i, linhasDaTabela = new Array();
                for (i = 0; i < $('.end_logradouro').length; i++) {

                    linhasDaTabela[i] = new Object(); // ESQUECI ESSA LINHA HEHEHE
                    linhasDaTabela[i].TBFUNCIONARIOID = $('.end_funcionarioid')[i].value;
                    linhasDaTabela[i].LOGRADOURO = $('.end_logradouro')[i].value;
                    linhasDaTabela[i].NUMLOGRADOURO = $('.end_numlogradouro')[i].value;
                    linhasDaTabela[i].COMPLEMENTO = $('.end_complemento')[i].value;
                    linhasDaTabela[i].BAIRRO = $('.end_bairro')[i].value;
                    linhasDaTabela[i].CEP = $('.end_cep')[i].value;
                }

                var funci = new Array();
                funci[0] = new Object();
                funci[0].TBFUNCIONARIOID = 0;
                funci[0].NMFUNCIONARIO = $("#NMFUNCIONARIO").val();
                funci[0].MATRICULA = "12312";
                funci[0].DTADMISSAO = $("#DTADMISSAO").val();
                funci[0].STATUS = false;
                funci[0].CPF = "13500305890";
                funci[0].TBEndereco = linhasDaTabela;

                $.ajax({
                    url: 'Novo',
                    datatype: 'json',
                    type: 'post',
                    tBFuncionario: funci,
                    contentType: 'application/json; charset=utf-8',
                    sucess: function () {
                        alert("Sucesso");
                    },
                    error: function (xhr, er) {
                        alert("Ocorreu erro!");
                    }
                });

The Controller who will receive the Employee and Address data:

public JsonResult Novo(TBFuncionario tBFuncionario)
        {

            if (ModelState.IsValid)
            {
                //_IRepositorio.InsereFuncionario(tBFuncionario);
                //return RedirectToAction("List");
            }

            return Json(tBFuncionario, JsonRequestBehavior.AllowGet);
        }

The problem is this: When I click on the Save button I run the Javascript snippet previously mentioned, see the result: inserir a descrição da imagem aqui

Beautiful the data is generated as expected, but in Controller the object returns empty:

inserir a descrição da imagem aqui

I really don’t know what else to do, anyone has any suggestions ??

  • Adriano, try to find the data to be sent as follows: $.param({ pComposicao: TBComposicao})

  • You can put the code of your Controller text in your question?

  • Hello Tobymosque I did the NCODE as you said and there was a breakthrough, the pComposicao model is sent but still the attributes remain null.

1 answer

1

The most immediate solution I was able to pass the parameters as text:

var TBCOMPOSICAOID = $("#TBCOMPOSICAOID").val();
                        

var DSCOMPOSICAO = $("#DSCOMPOSICAO").val();

$.getJSON("/Composicao/Novo/"
    , {
        pTBCOMPOSICAOID: TBCOMPOSICAOID,
        pDSCOMPOSICAO: DSCOMPOSICAO
      }
      , function (data) {
          var url = "/Administrativo/Composicao/List/";
          window.location.href = url;
      }).fail(function (jqxhr, textStatus, error) {
          var err = textStatus + ", " + error;
          alert('erro: ' + err.toString());
      });

public JsonResult Novo(int pTBCOMPOSICAOID, string pDSCOMPOSICAO)
{
    var model = new TBComposicao
    {
        TBCOMPOSICAOID = pTBCOMPOSICAOID,
        DSCOMPOSICAO = pDSCOMPOSICAO
    };

    _IRepositorio.AtualizarComposicao(model);
    return Json(model, JsonRequestBehavior.AllowGet);
}  

Thank you!

Browser other questions tagged

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