How do I know if a Json request returned no result?

0

I have a code in JavaScript that searches a database and fills a input with the name of the patient 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 a if so, if it does not have any results, it fills $("#bNome").val("PACIENTE NAO ENCONTRADO");

In my Controller I make the query in the bank like this:

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

I've tried:

if (!data){}
if (data == false){}
    
asked by anonymous 29.07.2017 / 21:40

1 answer

0

I was able to make a change in 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 .js looks 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);
    }
});
    
29.07.2017 / 23:43