在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;
        }

Ajax.BeginForm返回方法OnSuccess的更多相关文章

  1. ajax的使用:(ajaxReturn[ajax的返回方法]),(eval返回字符串);分页;第三方类(page.class.php)如何载入;自动加载函数库(functions);session如何防止跳过登录访问(构造函数说明)

    一.ajax例子:ajaxReturn("ok","eval")->thinkphp中ajax的返回值的方法,返回参数为ok,返回类型为eval(字符串) ...

  2. Ajax.BeginForm 不执行OnSuccess

    今天用MVC做了一个表单提交,使用Ajax.BeginForm ,但是碰到一个奇怪的问题OnSuccess回调函数不执行.后来经过多次尝试才发现要引用两个东西 1.<script src=&qu ...

  3. MVC4中Ajax.BeginForm OnSuccess 不执行以及控制器返回JsonResult 提示下载的原因

    这几天学习MVC的过程中,在学习Ajax.BeginForm时,一直遇到2个问题: 一. Ajax.BeginForm OnSuccess事件不执行 二.提交表单后,浏览器不识别json字符串,提示下 ...

  4. Ajax.BeginForm方法 参数

    感谢博主 http://www.cnblogs.com/zzgblog/p/5454019.html toyoung 在Asp.Net的MVC中的语法,在Razor页面中使用,替代JQuery的Aja ...

  5. MVC验证09-使用MVC的Ajax.BeginForm方法实现异步验证

    原文:MVC验证09-使用MVC的Ajax.BeginForm方法实现异步验证 MVC中,关于往后台提交的方法有: 1.Html.BeginForm():同步 2.Ajax.BeginForm():异 ...

  6. Ajax.BeginForm提示不支持live属性或方法的错误

    解决: 在nuget下载最新版本的jquery.unobtrusive-ajax.min.js文件 Ajax异步请求: 引用JS: <script type="text/javascr ...

  7. 取代Ajax.BeginForm的ajax使用方法

    原文:取代Ajax.BeginForm的ajax使用方法 一.前提概要 Asp.net core中已经取消了Ajax.BeginForm,也不会计划出ajax tag helper,所以得利用插件jq ...

  8. 在使用Ajax请求返回json数据的时候IE浏览器弹出下载保存对话框的解决方法

    在使用Ajax请求返回json数据的时候IE浏览器弹出下载保存对话框的解决方法 最近在做一个小东西,使用kindeditor上传图片的时候,自己写了一个上传的方法,按照协议规则通过ajax返回json ...

  9. MVC Ajax.BeginForm重复提交解决方法

    mvc使用MVC Ajax.BeginForm提交的时候有重复提交结果的时候检查相关js文件引用情况, 其中mvc4注意 1 2 3 4 @Scripts.Render("~/bundles ...

随机推荐

  1. 基于Selenium2+Java的UI自动化(4) - WebDriver API简单介绍

    1. 启动浏览器 前边有详细介绍启动三种浏览器的方式(IE.Chrome.Firefox): private WebDriver driver = null; private String chrom ...

  2. Android, JSONLIB , java.lang.NoClassDefFoundError: Failed resolution of: Lnet/sf/json/JSONArray; 原因

    出现这个错误的原因是因为引用的lib库的V4包与程序的V4包不兼容,替换成一致的包就OK了

  3. JDBC入门连接MySQL查数据

    在MySQL中建立user表,插入数据 create table user( id int, name varchar(10), age int )engine myisam charset utf8 ...

  4. Sql的实际应用

    sql实际应用-递归查询   1.既然要谈到sql,数据库表是必须的   2.数据结构     3.获取某个节点的所有子节点     传统的写法(sql2000) 很麻烦,暂且就不写了     来看看 ...

  5. jQuery Easy UI 使用

    一.引入必要文件 二.加载UI组件的方式 加载 UI 组件有两种方式: 1.使用 class 方式加载: 2.使用 JS 调用加载.//使用 class 加载,格式为: easyui-组件名 效果: ...

  6. mac 查看系统时区

    sudo systemsetup -gettimezone https://developer.apple.com/library/mac/documentation/Darwin/Reference ...

  7. c#解析Josn(解析多个子集,数据,可解析无限级json)

    首先引用 解析类库 using System; using System.Collections.Generic; using System.Linq; using System.Text; name ...

  8. java多线程之停止线程

    /*1.让各个对象或类相互灵活交流2.两个线程都冻结了,就不能唤醒了,因为根据代码要一个线程活着才能执行唤醒操作,就像玩木游戏3.中断状态就是冻结状态4.当主线程退出的时候,里面的两个线程都处于冻结状 ...

  9. 建造者模式(Builder Pattern)

    建造者模式:使用多个简单对象一步步构建成一个复杂的对象. 有时候,我们会创建一个“复杂”的对象,这个对象的由很多子对象构成,由于需求的变化,这个对象的各个部分经常面临剧烈的变化. 继续工厂模式的披萨店 ...

  10. sea.js说明文档

    Sea.js 手册与文档 首页 | 索引 目录 模块定义 define id dependencies factory exports require require.async require.re ...