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

0
Hello, I'm new in development, and I'm developing a data entry whereby the user type the system to search in the Api of the mail and the address related to the zip informed, but I've seen in many articles on the internet, but not I'm getting success 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) {

           }

       });

method no controller

    [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;
    }

But it is returning an empty object, I made several changes, but none worked. Can anyone give me a light of what might be wrong ??

    
asked by anonymous 06.09.2017 / 23:42

1 answer

0

Change the return to JsonResult in your method of your 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

07.09.2017 / 00:06