Pass parameters through jquery to controller

Asked

Viewed 7,019 times

1

I have a method in the controller(void) that receives some parameters(3). I am unable to pass to the method. The other times I did, passing to an object there, I have succeeded, with method returning a json. Well, this way is a void method and I don’t have an object as argument, but rather fields as arguments. See below the method and jquery. If there is possibility to work like this too, of course.

Controller: The [Httppost] attribute makes sense in this case?

[HttpPost]
public void GravaPainelPesquisa(string _cnpj, string _tecnico, string _obs)
{
     V99_WEBEntities db = new V99_WEBEntities();
     T_LogCadastroPDV logcadastro = new T_LogCadastroPDV();

     logcadastro.DE_Tecnico = _tecnico;
     logcadastro.DE_Obs = _obs;

     db.T_LogCadastroPDV.Add(logcadastro);
     db.SaveChanges();
 } 

My jquery:

function GravaPainelPesquisa() {

    var parametros = $('#txtCnpjPesquisa').val() + ',' + $('#txtTecnicoObs').val() + ',' + $('txtObservacao').val();

    $.ajax({

        url: 'Pesquisa/GravaPainelPesquisa',
        datatype: 'json',
        contentType: "application/json; charset=utf-8",
        type: "POST",
        data: JSON.stringify({  }),
        success: function (data) {

            //Aqui preciso chamar uma função que gera uma mensagem(não é um alert)
        },
        error: function (error) {
        }
    })
}

Function that generates the message:

$(function () {
   $("#dialogLogPdv").dialog();
});

I’m going to change the button, but just answer me one thing and see if I’m right. It’s a Submit button. What happens is that the parameters are coming empty. I put a break and observe, that only stops at break, after the form or the form controls are sent. After the fields are cleared, you enter the break, and if that’s what I’m thinking, the button sends everything and Zera the fields and then the method is already empty or null. This, I believe, is a feature of the button. Right or not?

I did so and managed to pass the values to the Controller:

var parametros = jQuery.parseJSON(' { "DE_CnpjPDV": "' + $("#txtCnpjPesquisa").val() + '" , "DE_tecnico": "' + $("#txtTecnicoObs").val() +
                                      '" , "DE_Obs": "' + $("#txtObservacao").val() + '"}');

And on the controller it’s like this:

[HttpPost]
        public void GravaPainelPesquisa(T_LogCadastroPDV logcadastro)
        {
            V99_WEBEntities db = new V99_WEBEntities();
            logcadastro.DT_Cadastro = DateTime.Now;

            db.T_LogCadastroPDV.Add(logcadastro);
            db.SaveChanges();
        } 

But you still make a mistake SaveChanges();

That is the mistake:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

And in the EntityValidationErrors I pick this up:

{System.Data.Entity.Validation.DbEntityValidationResult}

Inner Exception está null.

I found the bug. I created a Try.. catch and an Exception of the type: DbEntityValidationException and there I saw what the error is. It turns out, that in the view, the cnpj field has a mask and in the BD the field is a varchar(14), so you already know what happened. Size larger than supported.

2 answers

3


Create a json object to receive the values.

//Obj
 var parametros =
 {
  _txtCnpjPesquisa: $('#txtCnpjPesquisa').val() ,
  _txtTecnicoObs: $('#txtTecnicoObs').val(), 
  _txtObservacao: $('txtObservacao').val()
 }

 //Post
 $.post('GravaPainelPesquisa',function(retorno){

  });

Create a class variables must have the same name as the created object.

public class Parametros {
   string _txtCnpjPesquisa { get; set; }
   string _txtTecnicoObs { get; set; }
   string _txtObservacao { get; set; }
  }

[HttpPost]
public void GravaPainelPesquisa(Parametros parametros)
{
     V99_WEBEntities db = new V99_WEBEntities();
     db.T_LogCadastroPDV.Add(parametros);
     db.SaveChanges();
 } 
  • Your solution worked.

2

You must pass the parameters with the same type and name so that the Router, find and pass the parameters.

You should change the variable parameters like this:

// cria objeto JSON para ser serializado na chama ajax
var parametros = {
    _cnpj : $('#txtCnpjPesquisa').val(),
    _tecnico: $('#txtTecnicoObs').val(),
    _obs: $('#txtObservacao').val() // tava faltando também o #, se é no caso um id
};

And the call ajax to pass the parameters by ajax, in the POST:

$.ajax({
    url: 'Pesquisa/GravaPainelPesquisa',
    datatype: 'json',
    contentType: "application/json; charset=utf-8",
    type: "POST",
    data: JSON.stringify(parametros), // passe aqui o objeto por parâmetro no POST
    success: function (data) {
        //Aqui preciso chamar uma função que gera uma mensagem(não é um alert)
        // chama o dialog
        $("#dialogLogPdv").dialog();
    },
    error: function (error) {
    }
});

Complete method:

function GravaPainelPesquisa() {
    var parametros = {
        _cnpj : $('#txtCnpjPesquisa').val(),
        _tecnico : $('#txtTecnicoObs').val(),
        _obs : $('#txtObservacao').val()
    };

    $.ajax({
        url : 'Pesquisa/GravaPainelPesquisa',
        datatype : 'json',
        contentType : "application/json; charset=utf-8",
        type : "POST",
        data : JSON.stringify(parametros),
        success : function(data) {
            //Aqui preciso chamar uma função que gera uma mensagem(não é um alert)
            $("#dialogLogPdv").dialog();
        },
        error : function(error) {
        }
    });
}

Today, the way you posted, the parameters are not being passed, so it is impossible that they are passed to Controller

  • @pnet, it depends how you want this message, since an Alert does not serve, but then it is another question, you can take a look at the jQueryUI dialog

  • @pnet, I edited the answer from a look

  • @pnet, what error is occurring?

  • @pnet, the error must be in the context where this method is, there must be some (, without its closure )

  • @pnet, was missing also the # no $('#txtObservacao').val(), if it is an id

  • @pnet, this code is javascript, you’re seeing it right, it’s not C#?

  • @pnet, the code of the var parametros that is giving error you are putting where in javascript or C#?

  • Fernando, it also worked. It was the keys and not the parentheses, to work. OK, I passed, but the error at the time of recording continues. I’ll try with a using in my context to see if funf.

Show 3 more comments

Browser other questions tagged

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