I’m writing an ASP.NET application that requires users to log on to a server using an external API. I would like users to be given instant feedback, using Ajax, if they input invalid login credentials.
My view
@using (Ajax.BeginForm("Login", "Login", null, new { id = "login-form" }))
{
<label>
User Name: @Html.TextBox("userName", "", new { @class = "input" })
</label>
<label>
Password: @Html.Password("password", "", new { @class = "input" })
</label>
<input type="submit" class="button" value="Login" />
<div id="login-validate">Invalid Login!</div>
}
My controller
public ActionResult Login(string userName, string password)
{
// Returns true if connection is valid
if (RepoConnection.verifyAndBindConn(userName, password))
{
return Index(); // Redirect to home page, logged in as new user
}
else
{
return null; // TODO: Don't change view
}
}
Is there a way to have the controller not switch the view, and instead call a jQuery function to display the error message?
Just return
View()in your else block. It will redisplay the login page.If you really want it to be ajaxy, you are going to have to change your code to not use a form/submit button but to send your login credentials via ajax, write the session cookie, and handle the redirect in js code.