jquery method does not pass parameters to controller

Asked

Viewed 1,537 times

1

Jquery does not pass parameters to controller. Empty values.

Jquery:

function GravaEvento() {    
var str = "";
var parametros = jQuery.parseJSON('{ "DE_Cnpj": "' + $("#txtCnpj").val() + '" , "DE_Descricao": "' + $("#txtDescricao").val() + '" , "DE_UsuProxAcao": "' + $("#txtUsuarioProxAcao").val()
                                    + '" , "DE_UsuProxAcao": "' + $("#txtProxAcao").val() + '" , "DT_ProxAcao": "' + $("#txtDataCadastro").val()
                                    + '" , "ID_TipoProxAcao": "' + $("#txtDataCadastro").val() + '" }');

$.ajax({
    url: '/GerenciarPDV/GravaEvento',
    datatype: 'json',
    contentType: 'applicatio/json; charset=utf-8',
    type: 'POST',
    data: JSON.stringify({ _evento: parametros }),
    success: function (data) {

    },
    error: function () {

    }})
}

Controller

[HttpPost]
public JsonResult GravaEvento(T_CRM_Evento _evento)
{
    V99_WEBEntities db = new V99_WEBEntities();
    T_TecnicoExterno user = new T_TecnicoExterno();
    user = (T_TecnicoExterno)SessaoUtil.Recuperar("sessionUser");
    try
    {
        T_CRM_Evento evento = new T_CRM_Evento();

        evento.DE_Cnpj = _evento.DE_Cnpj;
        evento.DE_Descricao = _evento.DE_Descricao;
        evento.DE_Usuario = user.DE_Login;
        evento.DE_UsuProxAcao = _evento.DE_UsuProxAcao;
        evento.DT_Inclusao = DateTime.Now;
        evento.DT_ProxAcao = _evento.DT_ProxAcao;
        evento.ID_TipoProxAcao = _evento.ID_TipoProxAcao;

        db.T_CRM_Evento.Add(evento);
        db.SaveChanges();
    }
    catch(Exception ex)
    {
        string erro = ex.Message;
    }
    return Json(new { }, JsonRequestBehavior.AllowGet);
}

The function calls the controller, but does not pass the values. The T_TecnicoExterno is a BD entity mapped by my Entity. I thought about creating an object with the same fields, but I found this to repeat what already exists or not?

Jquery

function GravaEvento() {
    var parametros = { _cnpj: $('#txtCnpj').val(), _descricao: $("#txtDescricao").val() };    
    $.ajax({    
        url: '/GerenciarPDV/GravaEvento',
        datatype: 'json',
        contentType: 'applicatio/json; charset=utf-8',
        type: 'POST',
        data: JSON.stringify(parametros),
        success: function (data) {

        },
        error: function () {

        }
    })
}

Controller

[HttpPost]
public void GravaEvento(string _cnpj, string _descricao)
{
    V99_WEBEntities db = new V99_WEBEntities();
    try
    {
        T_CRM_Evento evento = new T_CRM_Evento();

        evento.DE_Cnpj = _cnpj;
        evento.DE_Descricao = _descricao;

        db.T_CRM_Evento.Add(evento);
        db.SaveChanges();
    }
    catch(Exception ex)
    {
        string erro = ex.Message;
    }
}
  • Change public JsonResult GravaEvento(T_CRM_Evento _evento) for public JsonResult GravaEvento(FormCollection collection). What happens?

  • I switched to void, because it is a method only for insertion in BD. I have another very similar to this and it works. I give an Alert with the values that comes from the page, I have the values, but when it comes to the controller, it is empty. I will edit and show how it was and still nothing. I don’t think it’s bootstrap, because in Alert I have the values of the guys.

  • Dude, try putting those notes in your controller: public JsonResult GravaEvento([FromBody]T_CRM_Evento _evento), why are you going through POST. Look here.

  • Po, but I have several methods similar to the one that are working. I don’t understand why.

2 answers

2


Use the method $.post which is simpler and works perfectly:

Javascript:

function GravaEvento() {
    $.post("/Home/GravaEvento",
        {
            DE_Cnpj: $("#txtCnpj").val(),
            DE_Descricao: $("#txtDescricao").val(),
            DE_UsuProxAcao: $("#txtUsuarioProxAcao").val(),
            ID_TipoProxAcao: $("#txtDataCadastro").val(),
            DT_ProxAcao: $("#txtDataCadastro").val()
        },
       function (data) {

       }, 'json');
} 

Method:

[HttpPost]
public JsonResult GravaEvento(T_CRM_Evento t_crm_evento)
{
    return Json(new { Status = true }, JsonRequestBehavior.DenyGet);
}

Debug:

inserir a descrição da imagem aqui

  • That way it worked, but I don’t understand why it didn’t work the other way. I have all my functions the other way. I work with dynamic html, that is, in the success of ajax I mount my page. As it keeps using the way Harry posted?

0

I have an example of a tcc I did once:

[HttpPost]
        public ActionResult CalendarData(FormCollection f)
        {

            string datainicio = Request.Form["data_inicio"];
            string datafinal = Request.Form["data_final"];
            int sala_id = int.Parse(Request.Form["sala_id"]);
            int turno_id = int.Parse(Request.Form["turno_id"]);

            IList<Reserva> tasksList = new List<Reserva>();
            tasksList = ReservaDAO.getEvents(datainicio, datafinal, sala_id, turno_id);


            return Json(tasksList, JsonRequestBehavior.AllowGet);
        }

See if it helps. Do the ajax the first way I sent it.

You can take the fields in C# this way:

        string DE_Cnpj = Request.Form["DE_Cnpj"];
        string DE_Descricao = Request.Form["DE_Descricao"];
        string DE_UsuProxAcao = Request.Form["DE_UsuProxAcao"];
        string DT_ProxAcao = Request.Form["DT_ProxAcao"];
        int ID_TipoProxAcao = int.Parse(Request.Form["ID_TipoProxAcao"]);

Try it this way:

function GravaEvento() {
    $.ajax({
      url: "/GerenciarPDV/GravaEvento",
      type: "POST",
      data: { "DE_Cnpj": $("#txtCnpj").val(), "DE_Descricao": $("#txtDescricao").val(), "DE_UsuProxAcao": $("#txtUsuarioProxAcao").val(), "DE_UsuProxAcao": $("#txtProxAcao").val(), "DT_ProxAcao": $("#txtDataCadastro").val(), "ID_TipoProxAcao": $("#txtDataCadastro").val() },
      dataType: "json", 
      success: function(data){
            console.log(data); //aparece o retorno no terminal
      }
    });
}

GravaEvento(); //executa a funcao

You can also pass the parameters at once on the date in this way:

data: $("form").serialize();
  • Keeps coming null

  • Sounds like the demo thing. It keeps coming null all and I don’t know what else to do.

Browser other questions tagged

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