Error 500 in ajax request with Asp.net mvc

Asked

Viewed 1,084 times

2

Good morning,

I got a problem I can’t fix. I made a simple ajax request in my code to fill the fields automatically if Cpf is already registered in the database.

Well, the day I did everything worked out and it was working great, but now out of the blue, he’s giving Error 500 and says q can’t find my Action and he enters the action, goes to the bank, gets the result, but when he returns he won’t go to View.

Can someone please help me?!

public class ParticipanteController : Controller
{
    mconfEntities db = new mconfEntities();
    // GET: Participante
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public JsonResult BuscaDados(string cpf)
    {
        string pesquisaCpf = cpf.Replace(".", "");

        var dados = db.Participante.FirstOrDefault(p => p.cpf == pesquisaCpf);

        return Json(dados);
    }

    public ActionResult Create()
    {
        var evento = db.Evento;

        ViewBag.conferencia = new SelectList(evento, "eventoUID", "descricao");

        return View();
    }

    [HttpPost]
    public ActionResult Create(Participante model)
    {
        if (ModelState.IsValid)
        {
            try
            {
                Participante p = new Participante()
                {
                    cpf = model.cpf,
                    nome = model.nome,
                    email = model.email,
                    telefone = model.telefone,
                    municipio = model.municipio,
                    unidadeSaude = model.unidadeSaude,
                    equipeSaude = model.equipeSaude,
                    categoriaProfissional = model.categoriaProfissional
                };

                db.Participante.Add(p);
                db.SaveChanges();

                return Redirect("http://www.google.com");
            }
            catch (EntityException ex)
            {
                TempData["erro"] = "Erro ao cadastrar participante - " + ex.Message;
                return View();
            }
        }
        else
        {
            TempData["erro"] = "Participante Inválido";
            return RedirectToAction("Create");
        }
    }
}


<script>
$(document).ready(

Function () { $('#Cpf'). focusout(Function() { Debugger; var cpfData = $('#Cpf'). val(). replace('.','). replace('-','');

      $.ajax
      ({
          url: '/Participante/BuscaDados/',
          type: "POST",
          data: { cpf: cpfData },
          success: function (data) {
              $('#nome').val(data.nome);
              $('#email').val(data.email);
              $('#telefone').val(data.telefone);
              $('#municipio').val(data.município);
              $('#unidadeSaude').val(data.unidadeSaude);
              $('#equipeSaude').val(data.equipeSaude);
              $('#categoriaProfissional').val(data.categoriaProfissional);
          }
      });
  });

});

The mistake:

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

  • 1

    Why post pictures of the code? Post the code. I’ll give you a hint on how to set a good example, follow the link: http://answall.com/help/mcve

  • Thanks for the tip, I’m new here. A question: I should delete this post and redo it or change it?

  • Do not need to delete, just edit. Note that below the question has 4 links: share, edit, close and flag. Use "Edit".

  • All right, I’m done with the amendment

2 answers

3

I went through something like this the other day,

Use the Fiddler program to verify which requests and which replies you are sending.

Regarding the error may be linked to the return type, try the return as follows:

return Json(dados, JsonRequestBehavior.AllowGet);

or

//retorna uma string json
return JavaScriptSerializer.Serialize(dados);

Now use Fiddler to verify that the response is being sent containing JSON

  • I downloaded Fiddler, what exactly do I have to check for? He made a mistake here but I don’t know what to send...

  • Open Fiddler and run your site, make the action that is giving problem be executed, as soon as you do so go to Fiddler and look for the answer that contains JSON, click on it and in the menu next navigate on the fields to analyze what is being sent

  • I did that, how can I send you the image? in part JSON it is written: JSON=Cpf ...

  • Update your question with the image of the JSON content of the answer by Fiddler

  • Add Jsonrequestbehavior.Allowget solves the problem. also remember to set the datatype: dataType: "json" to inform that your request will return a JSON.

  • @Ivanteles I added Behavior and dataType and continued the same problem. anyone with Skype?

  • I can only skype more at night, if by then you have not solved I comment here

  • All right, I’ll try to find a solution.

  • It also added Jsonrequestbehavior.Allowget?

  • How to search using Firstordefault() it can return null, Voce checked if this is not the case? What is the structure of the Participant class?

  • Ivan Teles Added yes @Fernandomedeiros He is returning data yes da para ver durante o debug no Visual Studio

Show 6 more comments

1


I was able to solve, after a few days without sleep and using the Fiddler that Fernando Medeiros indicated, I discovered that it was a Circular reference problem in the classes created by the Entity framework.

I solved by putting a .Select(t => new {t.nome, t.email, ...}) before . Where() and in this way he was able to identify which table I was trying to get the data.

The strangest thing about my case is that the day I made the Code the stop worked and suddenly stopped working...

Thank you very much to everyone who helped...

Solution:

[HttpGet]
    public JsonResult BuscaDados(string cpf)
    {      
        var dados = db.Participante.Select(t => new {t.cpf, t.nome, t.email, t.telefone, t.municipio, t.unidadeSaude, t.equipeSaude, t.categoriaProfissional } ).Where(p => p.cpf == cpf);

        return Json(dados, JsonRequestBehavior.AllowGet);
    }

Browser other questions tagged

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