C# Webmethod - Send and Receive the same object (custom) via Parametro

Asked

Viewed 931 times

1

My code:

Object:

public class Person
{

    private string _Nome;
    private DateTime _Nascimento;

    public string Nome { get { return _Nome; } }
    public DateTime Nascimento { get { return _Nascimento; } }

    public Person(string Nome, DateTime Nascimento)
    {
        _Nome = Nome;
        _Nascimento = Nascimento;
    }

}

My Website (Webmethods):

[WebMethod]
public static Person SendPerson()
{
    return new Person("Jhon Snow", DateTime.Now);
}

[WebMethod]
public static string ReceivePerson(Person oPerson)
{
    return "OK!";
}

My Javascript:

var Person;
GetPerson();
SendPersonBack();
function GetPerson()
{
    $.ajax({
        type: "POST",
        url: "frmVenda.aspx/SendPerson",
        data: {},
        contentType: "application/json; charset=utf-8",
        success: function (RequestReturn) {
            Person = RequestReturn.d;
            console.log(Person);
        },
        error: function (error) {
            alert(error.statusText);
        }
    });
}
function SendPersonBack()
{
    $.ajax({
        type: "POST",
        url: "frmVenda.aspx/ReceivePerson",
        data: JSON.stringify({"oPerson": Person}),
        contentType: "application/json; charset=utf-8",
        success: function (RequestReturn) {
            alert(RequestReturn.d);
        },
        error: function (error) {
            alert(error.statusText);
        }
    });
}

Imagem Recebendo o objeto normal mas erro ao enviar de volta

The object is normally sent to the clientside, but getting it back on the Server does not work! the object is the same that I sent, are the same properties.

Why can’t I get him back? Where is the problem?

2 answers

1


I solved the problem by creating a constructor with no parameters, setting all properties to string and adding the set method to all properties.

This caused . net to recognize the object coming via ajax and populate the normally error-free properties.

public class Person
    {

        private string _Nome;
        private string _Nascimento;

        public string Nome { get { return _Nome; } set { _Nome = value; } }
        public string Nascimento { get { return _Nascimento; } set { _Nascimento= value; } }

        public Person()
        {

        }

        public Person(string Nome, DateTime Nascimento)
        {
            _Nome = Nome;
            _Nascimento = Nascimento.ToString();
        }

    }

0

Dude, I think you should serialize. The problem that what your jquery sends back might be getting lost. I work in a similar way, but I use serialization to do it. See below an example of me. In my controller I have a method that runs a LINQ. The result of this LINQ, I serialize and send to my jquery function. See the controller: Note that I return a Json.

[HttpPost]
        public JsonResult PreencheCargo(int _resp)
        {
            RupturaEntities db = new RupturaEntities();

            var result_responsavel = db.Responsavel
                .Where(w => w.IDResponsavel == _resp)
                .Join(db.Nivel_Responsavel, r => r.IDNivel_Responsavel, n => n.IDNivel_Responsavel, (r, n) => new { r, n })
                .Join(db.Responsavel_Motivo, rm => rm.r.IDResponsavel, m => m.IDResponsavel, (rm, m) => new { rm, m })
                .Join(db.Responsavel_Unidade_Negocio, rn => rn.rm.r.IDResponsavel, un => un.IDResponsavel, (rn, un) => new { rn, un })
                .Join(db.Responsavel_TipoPDV, rtp => rtp.rn.rm.r.IDResponsavel, tp => tp.IDResponsavel, (rtp, tp) => new { rtp, tp})
                .Join(db.TipoPDV, tpdv => tpdv.tp.IDTipoPDV, tdv => tdv.IDTipoPDV, (tpdv, tdv) => new { tpdv, tdv})
                .Select(s => new { s.tpdv.rtp.rn.rm.r.IDResponsavel, s.tpdv.rtp.rn.rm.r.NM_Responsavel, s.tpdv.rtp.rn.rm.r.NM_Responsavel_Sigla, 
                                   s.tpdv.rtp.rn.rm.r.IDNivel_Responsavel,s.tpdv.rtp.un.Unidade_Negocio, s.tpdv.rtp.rn.m.Motivo, s.tdv.IDTipoPDV, s.tdv.Descricao }).ToList();

            return Json(new { result_responsavel }, JsonRequestBehavior.AllowGet);
        }

So now I have an object on the other side, bit by bit, that jquery will desiccate and work with the reconstructed object. My jquery function returns to my method in the same way, but I set a parameter to pass to the controller. I think this is no problem, but with me I do so. See below my jquery.

function CarregaDadosCargo(ajaxParameter) {

    $.ajax({

        url: '/CadastroCargo/PreencheCargo',
        datatype: 'json',
        contentType: 'application/json;charset=utf-8',
        type: 'POST',
        data: JSON.stringify({_resp: ajaxParameter}),
        success: function (data) {

            $.each(data, function (index, itemData) {
                $('#txtResponsavel').val(itemData.NM_Responsavel);
                $('#txtSigla').val(itemData.NM_Responsavel_Sigla);
                $('#cbxNivelResp option[value=' + itemData.IDNivel_Responsavel + ']').attr('selected', 'selected');
            })
        },
        error: function(error){
    }
    })
}

I don’t know if this will solve your problem, but with me I don’t have that kind of problems.

  • yes, I could get it back on the server as json string and convert it to Person object. But I didn’t want to have to do that, knowing that the object I send is the same one I’m getting. I wanted to understand why of the error.

Browser other questions tagged

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