1、先引用微软的 jquery.unobtrusive-ajax.min.js 插件
2、视图代码
@using (Ajax.BeginForm("Login_Ajax", "Login", new AjaxOptions { HttpMethod = "post", OnSuccess = "back" })) { <table border="0" cellpadding="0" cellspacing="2"> <tr> <td width="330" height="331"> </td> <td width="145"> </td> <td width="62"> </td> <td width="119"> </td> </tr> <tr> <td height="29"> </td> <td>@Html.TextBoxFor(s => s.UserName, new { @tabindex = "1", @class = "login_text" })</td> <td rowspan="2"> <button id="btnLogin" tabindex="3" class="button_1" type="submit" /> </td> <td rowspan="2">@Html.ActionLink("注册账号", "Register") </td> </tr> <tr> <td height="26"> </td> <td>@Html.PasswordFor(s => s.PassWord, new { @tabindex = "2", @class = "login_text" })</td> </tr> <tr> <td colspan="4" > <table> <tr> <td width="300"></td> <td>@Html.ValidationMessageFor(s => s.UserName)</td> </tr> <tr> <td width="300"></td> <td>@Html.ValidationMessageFor(s => s.PassWord)</td> </tr> </table> </td> </tr> </table> }
再在视图中加入ajax返回的js操作
<script type="text/javascript">
function back(data) {
if (data.Status == 0) {
alert(data.Msg);
return;
}
if (data.Status == 1) {
alert(data.Msg);
top.location = "/LedCheck/LedCheck/LedCheck";
}
}
</script>
3、控制器代码
public ActionResult Login_Ajax(UserInFo user)
{
string txt=null;
if (!ModelState.IsValid)
{
return Redirect("~/UserCtroll/Views/Shared/Error.cshtml");
}
UserInFo one = bll.Login(user.UserName, user.PassWord);
if (one == null)
{
txt = "用户名或密码不正确!";
Common.Method.AjaxBackInfo ajax = new Common.Method.AjaxBackInfo() { Status = 0, Msg = "登录失败,用户名或密码错误!" };
return Json(ajax);
}
else
{
txt = "欢迎您!" + one.UserName;
Session["userName"] = one.UserName;
Common.Method.AjaxBackInfo ajax =new Common.Method.AjaxBackInfo() { Status = 1, Msg = "登录成功!" };
return Json(ajax);
}
}
其中,创建了 ajax 返回对象,以json格式返回,下为 ajax对象的类
public class AjaxBackInfo { /// <summary> /// 返回信息 /// </summary> public string Msg{get;set;} /// <summary> /// 状态 /// </summary> public int Status { get; set; } }