Validating response in controller is giving error

Asked

Viewed 96 times

1

Need to validate the answer in my method in the controller. For this I need an if. Why does the method not consider the return within an IF? Thus:

public JsonResult ValidaLogin(string _email, string _senha)
        {
            INETGLOBALEntities db = new INETGLOBALEntities();
            bool validalogin = false;

            EncriptyDecripty cripto = new EncriptyDecripty();

            string s = cripto.Encrypt(_senha);

              var  result_login = (from login in db.tbl_usuario
                                    where login.email == _email && login.senha_usuario == _senha
                                    select new { login.email, login.nm_usuario }).ToList();

             if(result_login.Count > 0)
                return Json(new { result_login }, JsonRequestBehavior.AllowGet);
        }

Gives error, saying that the method does not have a return. As valid then?

Meu Ajax

function ValidaLogin() {

    $.ajax({
        url: '/Login/ValidaLogin',
        datatype: 'json',
        contentType: "application/json; charset=utf-8",
        type: "POST",
        data: JSON.stringify({ _email: $('#inputEmail').val(), _senha: $('#inputPassword').val() }),
        success: function (data) {

            $(window.document.location).attr('href', '/Pesquisa/Pesquisa');
        },
        error: function (error) {

            alert('Usuário ou senha digitados de forma incorreta.');
        }
    });

}

1 answer

2


Gives error because you really have no return if the condition of if does not check. A function of type JsonResult is always waiting for some kind of return. Makes:

if(result_login.Count > 0){
    return Json(new { result_login }, JsonRequestBehavior.AllowGet);
}else{
    return Json(JsonRequestBehavior.AllowGet);
}

Then in javascript you check if the variable result_login exists.

EDIT:

In your case you do:

function ValidaLogin() {    
    $.ajax({
        url: '/Login/ValidaLogin',
        datatype: 'json',
        contentType: "application/json; charset=utf-8",
        type: "POST",
        data: JSON.stringify({ _email: $('#inputEmail').val(), _senha: $('#inputPassword').val() }),
        success: function (data) {
            if(data != null){//Dá um alert do data para ver o que retorna. Possivelmente até pode dar undefined
                $(window.document.location).attr('href', '/Pesquisa/Pesquisa');
            }else{
                alert('Usuário ou senha digitados de forma incorreta.')
            }
        }
    });
}
  • I did so, Cesarmiguel and did not give error even in the controller(It was the lack of Else), but continues entering the ajax Success, ie redirecting to another page. Should not enter the error function?

  • Then you have to manipulate Success. Enter the code of your ajax

  • @pnet, updated response

Browser other questions tagged

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