我正在编写一个ASP.NET应用程序,要求用户使用外部API登录服务器。如果用户输入无效的登录凭据,我希望用户能够使用Ajax获得即时反馈。
我的观点
@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>
}
我的控制器
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
}
}
有没有办法让控制器不切换视图,而是调用jQuery函数来显示错误信息?
答案 0 :(得分:1)
只需在您的else块中返回View()
即可。它将重新显示登录页面。
if (RepoConnection.verifyAndBindConn(userName, password))
{
return Index(); // Redirect to home page, logged in as new user
}
else
{
return View(); // TODO: Don't change view
}
如果你真的希望它是ajaxy,你将不得不改变你的代码不使用表单/提交按钮,而是通过ajax发送你的登录凭据,编写会话cookie,并在js代码中处理重定向