User and password validation in Pop Up Modal using MVC 5

2

My problem is this. I have a modal login popup, as shown below. That when the user enters his login and password and clicks the login button, he calls my controller Authentic. Here is the code for my controller .

[HttpPost]
    public ActionResult Autentica(string login_username, string login_password)
    {
        TSF_USUARIOS usuario = usuarioDAo.BuscaPorLoginSenha(login_username, login_password);

        if(usuario!=null)
        {
            return RedirectToAction("Index","Home");
        }
        else
        {
            ModelState.AddModelError("login.invalido", "Usuário ou senha inválida.");
            return View();//Ainda procurando solução.
        }
    }

Iftheuserentersthecorrectinformationwillbedirectedtotheinitialscreen,untiltheneverythingok.Butifheentersthewronginformation,IneedtoinformhimofamessageinthisModal,thatismyproblem,thismodeisopenedwhentheuserclicksabuttoninthemenu.IfIgiveareturnview();,thepopupisclosed.I'musingbootstrap.jstodothemodalanimation.IsthereanywayIcandoitinthecontrollerreturnstheopenmodalandwiththemessagethatIaddedintheModelState?IhavealreadylookedforthisinformationinvariousforumsbutIhavenotbeenabletosolvemyproblem.

FollowmyModal:

<divclass="modal fade" id="login-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header" align="center">
                <img class="img-circle" id="img_logo" src="http://bootsnipp.com/img/logo.jpg"><buttontype="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
                </button>
            </div>
            <div id="div-forms">
                <form id="login-form" action="/Usuario/Autentica" method="post">
                    <div class="modal-body">
                        <div id="div-login-msg">
                            <div id="icon-login-msg" class="glyphicon glyphicon-chevron-right"></div>
                            <span id="text-login-msg">Informe seu nome de usuário e senha.</span>
                        </div>
                        <input id="login_username" name="login_username" class="form-control" type="text" placeholder="Login" required>
                        <input id="login_password" name="login_password" class="form-control" type="password" placeholder="Senha" required>
                        <div class="checkbox">
                            <label>
                                <input type="checkbox"> Salvar Senha
                            </label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <div>
                            <input type="submit" class="btn btn-primary btn-lg btn-block" value="Login" />
                        </div>
                        <div>
                            <button id="login_lost_btn" type="button" class="btn btn-link">Esqueceu a senha?</button>
                            @Html.ActionLink("Registrar", "Cadastro", "Usuario")
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
    
asked by anonymous 24.12.2015 / 22:54

1 answer

2

Modify your method to the following:

[HttpPost]
public JsonResult Autentica(string login_username, string login_password)
{
    TSF_USUARIOS usuario = usuarioDAo.BuscaPorLoginSenha(login_username, login_password);

    if(usuario!=null)
    {
        return Json(new { resultado = "Ok" }, JsonRequestBehavior.DenyGet)
    }

    return Json(new { resultado = "NaoEncontrado" }, JsonRequestBehavior.DenyGet);
}

Modify:

<input type="submit" class="btn btn-primary btn-lg btn-block" value="Login" />

To:

<button id="botao-login">Login</button>

Also implement View the following:

$("#botao-login").click(function () {
    $.ajax({
        type: "POST",
        url: "@Url.Action("Autentica", "MeuController")",
        data: {
            login_username: $("#login-username").val();
            login_password: $("#login-password").val();
        },
        dataType: "json",
        success: function (data) {
            if (data.resultado == "Ok") {
                window.location.replace("@Url.Action("Sucesso", "MeuController")");
            }

            // Exiba as mensagens de erro neste espaço. 
        }
    });
});

It's important to say that this is not the good way to do this. ASP.NET MVC has its own way of logging in using an authentication framework (preferably Identity). I just handily showed how to do it, but this way does not really authenticate your user.

    
25.12.2015 / 22:37