How to know if a Json request did not return result?

Asked

Viewed 156 times

0

I have a code in JavaScript who does a search in a database and fills in a input with the patient’s name found:

$("#bCns").keypress(function (e) {
    if (e.which == 13) {
        var options = {};
        options.url = "/Home/pegaPaciente";
        options.type = "GET";
        options.data = { "pCns": $("#bCns").val() };
        options.dataType = "json";
        options.success = function (data) {
            $("#pnPaciente").css("display", "block");
            $("#bNome").val(data.nome); //<<PREENCHE AQUI
        };
        $.ajax(options);
    }
});

I want to know how to make one if to, if there is no result, fill in $("#bNome").val("PACIENTE NAO ENCONTRADO");

In my Controller I make the appointment at the bank so:

public JsonResult pegaPaciente(string pCns)
{
paciente oPaciente = modelOff.pacientes.SingleOrDefault(p => p.cns == pCns);
return Json(oPaciente, JsonRequestBehavior.AllowGet);
}

I’ve tried to:

if (!data){}
if (data == false){}
  • This depends on what the database returns if there is no patient found.

  • I changed the question

1 answer

0


I managed to make a change in the Controller:

public JsonResult pegaPaciente(string pCns)
{
    paciente oPaciente = modelOff.pacientes.SingleOrDefault(p => p.cns == pCns);
    if (oPaciente == null)
        return Json("nao", JsonRequestBehavior.AllowGet);
    else
        return Json(oPaciente, JsonRequestBehavior.AllowGet);
}

And the .js was like this:

$("#bCns").keypress(function (e) {
    if (e.which == 13) {
        var options = {};
        options.url = "/Home/pegaPaciente";
        options.type = "GET";
        options.data = { "pCns": $("#bCns").val() };
        options.dataType = "json";
        options.success = function (data) {
        if (data == "nao"){
            alert("nada aqui");
            }
            else{
            $("#pnPaciente").css("display", "block");
            $("#bNome").val(data.nome); //<<PREENCHE AQUI
            }};
        $.ajax(options);
    }
});

Browser other questions tagged

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