Ajax.BeginForm返回方法OnSuccess

时间:2024-03-28 09:35:50

  在MVC3里面——程序集 System.Web.Mvc.dll, v4.0.30319有这么一个Ajax.BeginForm异步登录验证的类型,我们在下面给出一个例子:
在登录页面Logion.cshtml。使用@using (Ajax.BeginForm("Login", "Home", new AjaxOptions { HttpMethod = "Post", OnSuccess = "tips", OnBegin = "return ValidateLog()" })){提交Form内容},HttpMethod="提交方式",OnBegin="return validateLog()"是开始提交前,对Form表单的js验证。我们直接在javascript里面写validateLog()的js验证函数就可以了。OnSuccess = "tips"是Form表单成功提交到这个控制器后,然后再根据页面上的javascript函数tips(data)和它的返回值data,判断控制器里面回传过来的JsonResult值,是"true"还是"flase"。

[HttpPost]

public JsonResult Login(FormCollection collection){

string userName = collection["UserName"];

string passWord = collection["passWord"];

//经过数据库判断用户是否存在

//该用户有何权限

//用户和权限保存Session等等处理

JsonResult  json = new JsonResult();

json.Data = new Json{result="true"};  //给JsonResult对象赋值,登录结果是否通过

return json  //返回json值

}

1、用户登录页面Logion.cshtml

@{
    ViewBag.Title = "登录";
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <link href="/Style/index.css" rel="stylesheet" type="text/css" />
    <title>登录</title>
    <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/PleatedEffects.js" type="text/javascript"></script>
    <script src="/Scripts/RenzoManage.js" type="text/javascript"></script>
    <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    <script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    <script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        //登录验证
        function ValidateLog() {
            if (document.getElementById('userName').value == "" || document.getElementById('userName').value.length == 0) {
                alert('用户名不能为空');
                document.getElementById('userName').focus();
                return false;
            }
            if (document.getElementById('passWord').vaule == "" || document.getElementById('passWord').value.length == 0) {
                alert('密码不能为空');
                document.getElementById('passWord').focus();
                return false;
            }
        }

//登录回调函数
        function tips(data) {
            try {
                if (data.result == "false") {
                    alert("用户名和密码错误");
                }
                else {
                    location.href = '/Home/Index';
                }
            } catch (e) {
                alert('异常错误');
            }
        }
    </script>
</head>
<body>
    <div id="top">
        <div class="topbg">
            <div class="main_logo_wrap">
                <a href="#" class="logo" target="_blank" title="易乐国际">易乐国际</a></div>
            <div class="nav">
                <div class="floatright">
                    <a href="#" class="font01 marginright45 btn_time_a">@(DateTime.Now.GetDateTimeFormats('D')[1].ToString())</a>
                </div>
            </div>
        </div>
    </div>
    <div id="content" class="c">
        <div class="rightcontents">
            <div class="righttopbg right_wrap">
                <div class="righttopword">
                    您所在的位置: <a href="#">用户登录</a>
                </div>
            </div>
            <div class="righttable">
                @using (Ajax.BeginForm("Login", "Home", new AjaxOptions { HttpMethod = "Post", OnSuccess = "tips", OnBegin = "return ValidateLog()" }))             
                {
                    <table border="0" cellpadding="0" cellspacing="0" class="chaxunbiaoge search_wh">
                        <tr>
                            <td height="55px" width="80px" align="right">
                                用户名:
                            </td>
                            <td width="175px">
                                <input type="text" name="userName" id="userName" class=" biaogechaxunkuang"  tabindex="1"/>
                            </td>
                            <td>
                                <span class="colore6080d marginleft10">*</span> <span class="spanUserName"></span>
                            </td>
                        </tr>
                        <tr>
                            <td height="55px" align="right">
                                密码:
                            </td>
                            <td>
                                <input type="password" name="passWord" id="passWord" class=" biaogechaxunkuang" tabindex="2"/>
                            </td>
                            <td>
                                <span class="colore6080d marginleft10">*</span><span class="spanPassWord"></span>
                            </td>
                        </tr>
                        <tr>
                            <td height="55px" align="right">
                                &nbsp;
                            </td>
                            <td>
                                <input name="btnlogin" type="submit" class="marginleft10 btn_dl" value="登录" tabindex="3" style="margin-top: 14px;" />&nbsp;
                            </td>
                            <td>
                                &nbsp;
                            </td>
                        </tr>
                    </table>
                }
            </div>
        </div>
    </div>
    <div class=" clearfloat">
    </div>
    <div id="bottom">
        <div class="bottomwenzi">
            <span class="floatright">后台管理系统</span></div>
    </div>
</body>
</html>

2、用户登录控制器

///<summary>
         ///用户登陆
         ///</summary>
         ///<param name="collection"></param>
         ///<returns></returns>
        [HttpPost]
        public JsonResult Login(FormCollection collection)
        {
            string userName = collection["userName"];
            string passWord = collection["passWord"];
            JsonResult json = new JsonResult();
            try
            {
                Users user = UserManage.GetUser(userName, passWord);
                if (user != null)
                {
                    Session["LoginUser"] = user;
                    Roles role = AuthorityManage.GetRoleById(Convert.ToInt32(user.RoleID));
                    Session["AllowAuthority"] = role.AllowAuthority;
                    //Session["AllowMenu"] = role.AllowMenu;  //2013116
                    Session["RolesInfo"] = role;
                    int i = LogRecordsManage.Insert(new LogRecords() { LogMessage = role.Name + user.Username + "于" + DateTime.Now.ToString() + "登录", OperateID = user.ID, OperateTime = DateTime.Now, OperateType = 8 });
                    //json.Data = new { result = "true" };
                    json.Data = new { result = "false" };
                }
                else
                {
                    json.Data = new { result = "false" };
                }
            }
            catch (Exception ex)
            {
                Logs.AppLogs log = new Logs.AppLogs("Casino", "Login", userName, 2, ex.Message);
                log.Insert();
                CasinoWeb.Helper.LogMessage.SaveError(ex);
            }
            return json;
        }