How to call an Ajax controller method using MVC5 in visual studio?

Asked

Viewed 2,544 times

0

Hello, I’m new in development, and I’m developing a data entry where by zip code the user type the system search in the Mail Api and the address related to the zip code, but I’ve seen in many articles on the internet, but I’m not succeeding in functionality.

 $("#icon-cep").click(function () {
       var cep = $(".cep").val();
       console.log(cep);

       $.ajax({
           type: "POST",
           url: '@Url.Action("BuscaCep")',
           data: { cep: cep },
           success: function (result) {
               console.log(result);

           },
           error: function (result) {

           }

       });

controller method

    [HttpPost]
    public string BuscaCep(string cep)
    {
        WebServiceCorreio.AtendeClienteClient ws = new WebServiceCorreio.AtendeClienteClient("AtendeClientePort");
        var dados = ws.consultaCEP(cep);

        if (dados != null)
        {
            var json = JsonConvert.SerializeObject(dados);
            return json;
        }

        return null;
    }

However it is returning an empty object, I have made several changes, but none of them worked. Someone can give me a light of what might be wrong??

  • Change the return type of your action to Jsonresult

1 answer

0


Change the return to Jsonresult in your method of controller and use Json() to format this data, example:

Javascript:

$("#icon-cep").click(function() 
{
   var cep = $(".cep").val();
   console.log(cep);
   $.ajax({
       type: "POST",
       url: '@Url.Action("BuscaCep")',
       data: { cep: cep },
       success: function (result) {
           console.log(result);
       },
       error: function (result) {

       }
    });
}); 

Controller/Action

[HttpPost]
public JsonResult BuscaCep(string cep)
{
    WebServiceCorreio.AtendeClienteClient ws = 
              new WebServiceCorreio.AtendeClienteClient("AtendeClientePort");
    var dados = ws.consultaCEP(cep);

    if (dados != null)
    {       
        return Json(dados);
    }

    return null;
}

References

  • 1

    Face solved, my problem, was really, lost, thank you so much for helping.

Browser other questions tagged

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