Ajax 登录控件(二)

来源:互联网 发布:免费超市收银软件 编辑:程序博客网 时间:2024/05/21 08:00
上一章的 Ajax登录控件有一个隐含的问题,就是不能在一个页面中同时放两个AjaxLogin。且 RemberMe一定要有。
现在修改了这个问题。不过还是有点问题。如果发现问题请在后面跟帖。
--------------------在IE7,Firefox2.0下测试过。(其余的没测试)
---------------------------AjaxLogin.cs-----------源码如下
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace AjaxControl
{
    /// <summary>
    ///AjaxLogin 的摘要说明
    /// </summary>
    public class AjaxLogin:CompositeControl
    {
       private AjaxLoginContainer _templateContainer;
        private ITemplate _loginTemplate;
        [PersistenceMode(PersistenceMode.InnerProperty ),TemplateContainer(typeof(AjaxLogin ))]
        public ITemplate LayoutTemplate
        {
            get
            {
                return this._loginTemplate;
            }
            set
            {
                this._loginTemplate =value;
                base.ChildControlsCreated = false;
            }
        }
        public AjaxLogin()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }

        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!Page.ClientScript.IsClientScriptBlockRegistered(Page.GetType(), "js4ajaxLoginControl"))
            {
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "js4ajaxLoginControl", "<script language=/"javascript/" type=/"text/javascript/" src=/"ajaxLogin.js/" ></script>", false);
            }
        }

        protected override void CreateChildControls()
        {
            this.Controls.Clear();
            this._templateContainer = new AjaxLoginContainer(this);
            ITemplate layoutTemplate = this.LayoutTemplate;
            if (layoutTemplate == null)
            {
                this._templateContainer.EnableViewState = false;
                this._templateContainer.EnableTheming = false;
                layoutTemplate = new AjaxLoginTemplate(this);
            }
            layoutTemplate.InstantiateIn(this._templateContainer);
            this.Controls.Add(this._templateContainer);
        


        }
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
        
            if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(), this.UniqueID))
            {
                Control uLv = this.FindControl("LoginView");
                Control uLs = this.FindControl("LoginStatus");
                Control uName = this.FindControl("UserName");
                Control uPwd = this.FindControl("Password");
                Control uLi = this.FindControl("LoginIn");
                Control uLo = this.FindControl("LoginOut");
                Control uCs = this.FindControl("CurrentUser");
                Control uRm = this.FindControl("RememberMe");
                string uRmId = "";
                if (uRm == null)
                {
                    uRmId = "";
                }
                else
                {
                    uRmId = uRm.ClientID;
                }



                AjaxLoginContainer ajc = this._templateContainer;
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.AppendLine("<script language=/"javascript/" type=/"text/javascript/">");
                sb.AppendFormat("var jx_{0}=new ajaxLogin(/"{0}/",/"{1}/",/"{2}/",/"{3}/",/"{4}/",/"{5}/",/"{6}/",/"{7}/",/"{8}/");",
                                     this.ClientID, uLv.ClientID, uName.ClientID, uPwd.ClientID, uLi.ClientID,
                                     uLs.ClientID, uCs.ClientID, uLo.ClientID,uRmId);
                sb.AppendFormat("jx_{0}.isOnline(jx_{0}.onCheckUserCompleted,jx_{0}.onHttpStatusError);", this.ClientID);
                sb.AppendFormat("</script>");
                Page.ClientScript.RegisterStartupScript(this.GetType(), this.UniqueID, sb.ToString(), false);


            }
        }
        private sealed class AjaxLoginTemplate : ITemplate
        {
            private AjaxLogin _owner;

            public AjaxLoginTemplate(AjaxLogin owner)
            {
                this._owner = owner;
            }

            #region ITemplate 成员

            public void InstantiateIn(Control container)
            {
             

            }

            #endregion

            private void CreateControls(AjaxLoginContainer loginContainer)
            {
                TextBox tb = new TextBox();
                tb.ID = "UserName";
                tb.TextMode = TextBoxMode.SingleLine;
                loginContainer.UserName = tb;

                TextBox pwd = new TextBox();
                pwd.ID = "Password";
                pwd.TextMode = TextBoxMode.Password;
                loginContainer.Password = pwd;

                Button lgIn = new Button();
                lgIn.ID = "LoginIn";
                lgIn.Text = "登录";
                lgIn.UseSubmitBehavior = false;
                loginContainer.LoginInButton = lgIn;

                CheckBox cb = new CheckBox();
                cb.ID = "RememberMe";
                cb.Text = "RememberMe";
                loginContainer.RememberMe = cb;


                Label lgN = new Label();
                lgN.ID = "CurrentUser";
                lgN.Text = "";
                loginContainer.CurrentUser = lgN;

                Button lgOut = new Button();
                lgOut.ID = "LoginOut";
                lgOut.Text = "注销";
                lgOut.UseSubmitBehavior = false;
                loginContainer.LoginOutButton = lgOut;

                Panel lgView = new Panel();
                lgView.ID = "LoginView";
                loginContainer.LoginView = lgView;

                Panel lgStatus = new Panel();
                lgStatus.ID = "LoginStatus";
                loginContainer.LoginStatus = lgStatus;



            }

        }
        internal sealed class AjaxLoginContainer : WebControl
        {
            public TextBox UserName;
            public TextBox Password;
            public CheckBox RememberMe;
            public Button LoginInButton;

            public Label CurrentUser;
            public Button LoginOutButton;

            public Panel LoginView;
            public Panel LoginStatus;

            private AjaxLogin _owner;
            public AjaxLoginContainer(AjaxLogin owner)
            {
                _owner = owner;
            }
            public override void RenderBeginTag(HtmlTextWriter writer)
            {

            }
            public override void RenderEndTag(HtmlTextWriter writer)
            {

            }
           
        }
    }
  
}
-------------------------------ajaxLogin.js----------------------------
function $(id){ return document.getElementById(id);};
           function $F(id) { return $(id).value;};
           function $Event(id,eventName,funName){
                  var o=$(id);
                  if(!o["evtAdd"])
                  {
                     //o.detachEvent ? o.detachEvent("on"+eventName,funName ): o.removeEventListener(eventName ,funName ,false );
                     o.attachEvent ? o.attachEvent("on"+eventName,funName):o.addEventListener(eventName,funName,false   );
                     o["evtAdd"]=true ;
                  }
           }
           function $Text(id,msg){
                  var o=$(id);
                  o.innerHTML=msg;
           }
           String.prototype.trim = function()     
           {     
                var t = this.replace(/(^/s*)|(/s*$)/g, "");   
                return t.replace(/(^ *)|( *$)/g, "");   
           }

           function messageData(httpResponseText){
                this.responseText=httpResponseText;
                var code=0;
                var desc="";
                this.msgCode=function(){
                     var  tmp="";
                     try
                     {
                        tmp=this.responseText.substring(0,2);
                     }
                     catch(e)
                     {
                      
                     }
              
                     switch(tmp )
                     {
                                  case "0:":
                                     code =0;
                                     break;
                                  case "1:":
                                     code =1;
                                     break ;
                                  case "2:":
                                     code =1;
                                     break ;
                                  case "3:":
                                     code =1;
                                     break ;
                                  case "4:":
                                     code =1;
                                     break ;
                                 case "5:":
                                     code =5;
                                     break;
                                 default:
                                     code =-1;
                                     break ;
                     }
                     return code ;
                }
                this.msgDesc=function(){
                     try
                     {
                        desc =this.responseText.substring(2);
                     }
                     catch(e)
                     {
                     }
                     return desc ;
                   
                }
           }
           function ajaxLogin(lgoinViewId,loginCtrlId,lgUserName,lgUserPwd,lgCmd,loginStatusId,loginStatusName,loginOutId,loginRemberMe){
             
                 this.loginViewId=lgoinViewId ;

                 this.loginControlId=loginCtrlId ;
                 this.loginUserName=lgUserName ;
                 this.loginPassword=lgUserPwd ;
                 this.loginButton=lgCmd ;
             
                 this.loginStatusId=loginStatusId ;
               
                 this.loginStatusName=loginStatusName ;
                 this.loginOutButton=loginOutId ;
         
                 this.loginRemberMeId=loginRemberMe;
                 var cTh=this ;
                
                 if(typeof ajaxLogin.__RegisteredView =="undefined"){
                       ajaxLogin.__RegisteredView=new Array ();
                 }
                 ajaxLogin.__RegisteredView.push(this);

                

                 this.init=function(){
                        var http=false ;
                        if(typeof ActiveXObject !="undefined"){
                            try
                            {
                                http=new ActiveXObject("Msxml2.XMLHTTP");
                            }
                            catch(e)
                            {
                                try
                                {
                                    http=new ActiveXObject("Microsoft.XMLHTTP");
                                }
                                catch(E)
                                {
                                    http=false ;
                                }
                            }
                        } else if(XMLHttpRequest ){
                               try
                               {
                                   http=new XMLHttpRequest();
                               }
                               catch(e)
                               {
                                  http=false ;
                               }
                        }
                        if(http)
                        {
                          
                            $Event(cTh.loginButton,"click",cTh.loginClick );
                            $Event(cTh.loginOutButton ,"click",cTh.loginOutClick );
                            $Event(cTh.loginUserName ,"keydown",cTh.nameKeyDown);
                            $Event(cTh.loginPassword ,"keydown",cTh.pwdKeyDown);
                        }
                        return http ;
                 }
                 this.showIn=function(){
                        $(cTh.loginControlId).style.display="none";
                        $(cTh.loginStatusId).style.display="";
                 }
                 this.showOut=function(){
               
                        $(cTh.loginStatusId).style.display="none";
                        $(cTh.loginControlId).style.display="";
                 }
                 this.clear=function(){
                     $(cTh.loginUserName ).value="";
                     $(cTh.loginPassword ).value="";
                     try
                     {
                        $(cTh.loginRemberMeId ).checked=false ;
                     }
                     catch(e)
                     {
                     }
                 }
               
                 this.loginOut=function(onCompleted,onRunning,onError){
                         var http=cTh.init();
                         if(!http)
                          return ;
                         http.open("GET","LoginOut.aspx",true);
                         http.onreadystatechange=function(){
                                if(http.readyState==4){
                                     if(http.status==200){
                                        onCompleted();
                                     } else {
                                        onError();
                                     }
                                } else {
                                     onRunning();
                                }
                         }
                         http.send(null);
                 }
               
                 this.loginOutComplected=function(){
                         var   regView =ajaxLogin.__RegisteredView;
                         for(var i=0;i<regView.length;i++)
                         {
                            regView[i].showOut ();
                         }
//这个是为了防止同一用户在不同的机子上同时登录用的。
                         if( ajaxLogin.__ssoTimeId  )
                         {
                           window.clearInterval(  ajaxLogin.__ssoTimeId  );
                         }

                 }
                 this.loginOutRunning=function(){
                 }
                 this.loginOutErr=function (){
                 }
                 //单击事件的处理
                 this.loginClick=function(evt){
              
                        var name=$F(cTh.loginUserName );
                        var pwd=$F(cTh.loginPassword );
                       
                        name=name.trim();
                        if(name ==""){
                              alert("用户名不能为空");
                              $(cTh.loginUserName).focus();
                              if(window.event){
                                    window.event.returnValue=false ;
                              } else {
                                    evt.preventDefault();
                              }
                              return ;
                        }
                        pwd=pwd.trim();
                        if(pwd ==""){
                             alert("密码不能为空");
                             $(cTh.loginPassword ).focus();
                             if(window.event){
                                    window.event.returnValue=false ;
                              } else {
                                    evt.preventDefault();
                              }
                              return ;
                        }
                    
                        var rm="0"
                        try
                        {
                          rm=$(cTh.loginRemberMeId ).checked   ?  "1":"0";
                        }
                        catch(e)
                        {
                        }
                        cTh.login(name ,pwd,rm,cTh.onLoginCompleted ,cTh.onHttpStatusError ,cTh.onLoginRunning);
                        if(window.event){
                             window.event.returnValue=false ;
                        } else {
                            evt.preventDefault();
                        }
                 }
                 this.loginOutClick=function(evt){
                        cTh.loginOut(cTh.loginOutComplected ,cTh.loginOutRunning ,cTh.loginOutErr);
                        if(window.event){
                             window.event.returnValue=false ;
                        }   else {
                            evt.preventDefault();
                        }
                 }
                 //keydown事件的处理
                 this.nameKeyDown=function (evt){
                       var srcObject;
                       if(window.event){
                               srcObject =event.srcElement;
                               if(event.keyCode==13 ){
                                   $(cTh.loginPassword ).focus();
                                   event.returnValue=false ;
                               }
                       } else {
                               srcObject =evt.target;
                               if(evt.keyCode==13){
                                   $(cTh.loginPassword ).focus();
                                   evt.returnValue=false ;
                               }
                       }
                     
                 }
                 this.pwdKeyDown=function(evt){
                       var srcObject;
                       if(window.event){
                               srcObject =event.srcElement;
                               if(event.keyCode==13 ){
                                   $(cTh.loginButton).click();
                                   event.returnValue=false ;
                               }
                       } else {
                               srcObject =evt.target;
                               if(evt.keyCode==13){
                                   $(cTh.loginButton ).click();
                                   evt.returnValue=false ;
                               }
                       }
                 }
                
              
                 this.login=function(userName,passwrod,remberMe,onCompletedCallback,onErrorCallback,onRunningCallback){
                       var http= cTh.init();
                       if(!http)
                        return
                       http.open("POST","Login.aspx",true );
                       http.onreadystatechange=function(){
                            var state=http.readyState;
                            if(http.readyState==4){
                               if(http.status==200){
                                    onCompletedCallback(http.responseText);
                               } else {
                                    onErrorCallback(http.status);      
                               }
                            } else {
                               if(onRunningCallback ){
                                   onRunningCallback(state);
                               }
                            }
                       }
                       var params="UserName="+escape(userName)+"&Password="+ escape (passwrod )+"&RememberMe="+remberMe;
                        http.send(params);
                 }
                 this.onLoginRunning=function (state){
                 }
                 this.onLoginCompleted=function(data){
                 debugger
                      var msg=new messageData(data);
                      var code=msg.msgCode ();
                      debugger
                      var desc=msg.msgDesc ();
                       switch(code )
                      {
                             case 0:
                               var regView=ajaxLogin.__RegisteredView;
                               for(var i=0;i<regView.length;i++){
                                     regView[i].showIn();
                                     $Text(regView[i].loginStatusName,desc );
                                     regView[i].clear();
                               }
                               if(typeof ajaxLogin.__ssoTimeId =="undefined"  )
                               {
                                  ajaxLogin.__ssoTimeId  = window.setInterval(cTh.notifyServer,1000);
                               }
                               break ;
                             case 1:
                             case 2:
                             case 3:
                             case 4:
                             case 5:
                                alert(desc);
                                break;
                             default :
                                alert("浏览器脚本错误");
                                break ;
                              
                      }
                 }
///用于通知服务器当前用户在线,具体的实现等过几天在贴出来。
                this.notifyServer=function(){
                       var d=new Date();
                       document.title="I'm online "+d.toString ();
       }

                 this.isOnline=function(onCompletedCallback,onErrorCallback){
                      var http=cTh.init ();
                      if(!http )
                         return false ;
                      http.open("GET","Chk.aspx",true );
                      http.onreadystatechange=function(){
                          var state=http.readyState;
                          if(http.readyState==4){
                             if(http.status==200){
                                onCompletedCallback(http.responseText);
                             } else {
                                 onErrorCallback(http.status);
                             }
                          }
                      }
                      http.send(null);
                 }
                 this.onCheckUserCompleted=function(data){
                        var msg=new messageData(data );
                        var code=msg.msgCode ();
                        var regView=ajaxLogin.__RegisteredView;
                        switch(code )
                        {
                             case 0:
                                 for(var i=0;i<regView.length;i++)
                                 {
                                    regView[i].showIn ();
                                    $Text(regView[i].loginStatusName ,msg.msgDesc ());
                                 }
                                break;
                             case 1:
                                 for(var i=0;i<regView.length;i++)
                                 {
                                    regView[i].showOut ();
                                    $Text(regView[i].loginStatusName ,"");
                                 }
                                break;
                             default:
                                break;
                        }
                 }
                 this.onHttpStatusError=function(status){
                       alert("服务器错误:"+status );
                 }
           }
原创粉丝点击