调用JS

2010-04-22using System.Web;
using System.Web.UI;
using System.Text;
 
 

public abstract class JS
      {
          /** <summary>
          /// 客户端打开窗口
          /// </summary>
          /// <param name="strUrl"></param>
          public static void OpenWindow(string strUrl)
          {
              HttpContext.Current.Response.Write("<script language=javascript>");
             HttpContext.Current.Response.Write("window.open('" + strUrl + "');");
             HttpContext.Current.Response.Write("</script>");
            
         }
         /** <summary>
         /// 输出自定义脚本信息
         /// </summary>
         /// <param name="page">当前页面指针,一般为this</param>
         /// <param name="script">输出脚本</param>
         public static void ResponseScript(System.Web.UI.Page page,string script)
         {
             page.RegisterStartupScript("message","<script language='javascript' defer>"+script+"</script>");
         }
         /** <summary>
         /// 显示消息提示对话框,并进行页面跳转
         /// </summary>
         /// <param name="page">当前页面指针,一般为this</param>
         /// <param name="msg">提示信息</param>
         /// <param name="url">跳转的目标URL</param>
         public static void ShowAndRedirect(System.Web.UI.Page page,string msg,string url)
         {
             StringBuilder Builder=new StringBuilder();
             Builder.Append("<script language='javascript' defer>");
             Builder.AppendFormat("alert('{0}');",msg);
             Builder.AppendFormat("top.location.href='{0}'",url);
             Builder.Append("</script>");
             page.RegisterStartupScript("message",Builder.ToString());
         }
 
 
         public static void  ShowConfirm(System.Web.UI.WebControls.WebControl Control,string msg)
         {
             Control.Attributes.Add("onclick", "return confirm('" + msg + "');") ;
         }
         /** <summary>
         /// 清空所有panel里面的textbox内容
         /// </summary>
         /// <param name="pan"></param>
         public static void clearAll(System.Web.UI.WebControls.Panel pan)
         {           
             foreach (Control panl in pan.Controls )
             {
                 if(panl.GetType().ToString()=="System.Web.UI.WebControls.TextBox")
                 {
                     ((System.Web.UI.WebControls.TextBox)panl).Text="";
                 }
             }
         }
         
         /** <summary>
         ///  窗体加载以后探出对话框
         ///  </summary>
         public static void Alert(string msg)
         {
             Page pages;
             pages= HttpContext.Current.Handler as System.Web.UI.Page;
             msg=msg.Replace("'","");
             msg=msg.Replace("/"","");
             msg=msg.Replace("/n",@"/n").Replace("/r",@"/r").Replace("/"",@"/""") ;
 
             pages.Controls.Add(new System.Web.UI.LiteralControl("<script language=javascript>alert('" + msg + "');</script>"));
         }
         /** <summary>
         /// 窗体没有加载的时候如pageload的时候探出对话框
         /// </summary>
         public static void Alert_none(string msg)
         {
             Page pages;
             pages= HttpContext.Current.Handler as System.Web.UI.Page;
             msg=msg.Replace("'","");
             msg=msg.Replace("/"","");
             msg=msg.Replace("/n",@"/n").Replace("/r",@"/r").Replace("/"",@"/""") ;
             string retu = " alert('" + msg + "');";
             ClientWrite2( retu);
         }
         /** <summary>
         /// 加载以后写自己的脚本
         /// </summary>
         /// <param name="pages"></param>
         /// <param name="yourJs"></param>
         public static void ClientWrite(string yourJs)
         {
             Page pages;
             pages= HttpContext.Current.Handler as System.Web.UI.Page;
             pages.Controls.Add(new System.Web.UI.LiteralControl("<script language=javascript>" + yourJs  + "</script>"));
         }
         /** <summary>
         /// 加载以前写自己的脚本
         /// </summary>
         /// <param name="pages"></param>
        /// <param name="yourJs"></param>
        public static void ClientWrite2(string yourJs)
        {
            Page pages;
            pages= HttpContext.Current.Handler as System.Web.UI.Page;
            pages.Response.Write("<script language=javascript>");
            pages.Response.Write(yourJs );
            pages.Response.Write(" </script>");
        }

        /** <summary>
        /// 得到刷新界面的字符串
        /// </summary>
        /// <returns></returns>
        public static string  RefreshWin()
        {
            return "window.location=window.location.href;";
        }
        /** <summary>
        /// 打开小窗体
        /// </summary>
        /// <param name="url"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="top"></param>
        /// <param name="left"></param>
        public static void OpenLittleWindow(string url,int width,int height,int top,int left)
        {
            string str;
            str = "javascript:var popup;popup=window.open('{url}',null,'scrollbars=yes,status=no,width={width},height={height},top={top},left={left}');popup.opener=self.opener;self.close();";
            str = str.Replace("{width}", width.ToString());
            str = str.Replace("{height}", height.ToString());
            str = str.Replace("{top}", top.ToString());
            str = str.Replace("{left}", left.ToString());
            str=str.Replace("{url}",url);   
        }

        /** <summary>
        /// 回车-〉tab
        /// </summary>
        /// <param name="page"></param>
        public static void ToTab()
        {
            Page page;
            page= HttpContext.Current.Handler as System.Web.UI.Page;
            System.Text.StringBuilder scriptFunction=new StringBuilder();
            scriptFunction.Append("<script language='javascript'>");
            scriptFunction.Append("       function returnTotab()");
            scriptFunction.Append("         {");
            scriptFunction.Append("          if(event.keyCode==13)    ");
            scriptFunction.Append("             {event.keyCode=9;     ");
            scriptFunction.Append("               return true;}       ");
            scriptFunction.Append("          } ");
            scriptFunction.Append("</script>");
            page.RegisterStartupScript("totab", scriptFunction.ToString());
           
        }
        /** <summary>
        /// tab->enter
        /// </summary>
        /// <param name="page"></param>
        public static void tabToEnter()
        {
            Page page;
            page= HttpContext.Current.Handler as System.Web.UI.Page;
             System.Text.StringBuilder scriptFunction=new StringBuilder();
            scriptFunction.Append("<script language='javascript'>");
            scriptFunction.Append("    function Tcheck()");
            scriptFunction.Append("         {");
            scriptFunction.Append("         if(event.keyCode==8||event.keyCode==9) ");
            scriptFunction.Append("          return true;");
            scriptFunction.Append("         else ");
            scriptFunction.Append("         {");
            scriptFunction.Append("          if(((event.keyCode>=48)++(event.keyCode<=57))||((event.keyCode>=96)++(event.keyCode<=105)))");
            scriptFunction.Append("              return true;");
            scriptFunction.Append("          else");
            scriptFunction.Append("          if(event.keyCode==13||event.keyCode==110||event.keyCode==190||event.keyCode==39)");
            scriptFunction.Append("             {event.keyCode=9;");
            scriptFunction.Append("               return true;}");
            scriptFunction.Append("            else");
            scriptFunction.Append("              return false;");
            scriptFunction.Append("        }");
            scriptFunction.Append("          }     ");
            scriptFunction.Append("</script>");
            page.RegisterStartupScript("switch", scriptFunction.ToString());
        }
        /** <summary>
        /// attachEvent
        /// </summary>
        /// <param name="controlToFocus"></param>
        /// <param name="page"></param>
        public static void attachEvent(Control[] controlToFocus)
        {
            Page page;
            page= HttpContext.Current.Handler as System.Web.UI.Page;
             System.Text.StringBuilder scriptFunction=new StringBuilder();
            string scriptClientId;
            scriptFunction.Append("<script language='javascript'>");
            
            foreach(Control con in controlToFocus)
            {
                scriptClientId = con.ClientID;
                scriptFunction.Append("document.getElementById('" + scriptClientId + "').attachEvent('onkeydown', Tcheck);");
            }
            scriptFunction.Append("</script>");
            page.RegisterStartupScript("attach", scriptFunction.ToString());
        }
        /** <summary>
        ///
        /// </summary>
        /// <param name="controlToFocus"></param>
        /// <param name="page"></param>
        /// <param name="eventStr"></param>
        /// <param name="FuncStr"></param>
        public static void AttachEvent(Control[] controlToFocus,string eventStr,string FuncStr)
        {
            Page page;
            page= HttpContext.Current.Handler as System.Web.UI.Page;
            System.Text.StringBuilder scriptFunction=new StringBuilder();
            string scriptClientId;
            scriptFunction.Append("<script language='javascript'>");
            foreach(Control con in controlToFocus)
            {
                scriptClientId = con.ClientID;
                scriptFunction.Append("document.getElementById('" + scriptClientId + "').attachEvent('" + eventStr + "', " + FuncStr + ");");
            }
            scriptFunction.Append("</script>");
            page.RegisterStartupScript("attach2", scriptFunction.ToString());
        }
        /** <summary>
        ///
        /// </summary>
        /// <param name="page"></param>
        public static void NumOnlyFun()
        {
            Page page;
            page= HttpContext.Current.Handler as System.Web.UI.Page;
            System.Text.StringBuilder scriptFunction=new StringBuilder();
            scriptFunction.Append("<script language='javascript'>");
            scriptFunction.Append("       function isNum()");
            scriptFunction.Append("         {");
            scriptFunction.Append("              if(event.keyCode==8||event.keyCode==9) ");
            scriptFunction.Append("                  return true;");
            scriptFunction.Append("             else ");
            scriptFunction.Append("             {");
            scriptFunction.Append("          if(((event.keyCode>=48)++(event.keyCode<=57))||((event.keyCode>=96)++(event.keyCode<=105)))");
            scriptFunction.Append("              return true;");
            scriptFunction.Append("          else");
            scriptFunction.Append("                return false;");
            scriptFunction.Append("        }");
            scriptFunction.Append("          } ");
            scriptFunction.Append("</script>");
            page.RegisterStartupScript("numonly", scriptFunction.ToString());
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如何封装JS和CSS文件为服务器端控件---ASP.NET 2.0 我们以封装一个JS的日期控件为列子,将它和服务器的TextBox结合在一起做成一个服务器控件,以达到直接托上去就可以使用的效果。其实很简单,大家共同学习。先看看效果图: 方法: 首先:下载一个JS的日期组件,带封装。 然后:建一个日期类文件CalendarBox.cs代码如下: using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web; using System.Drawing; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; [assembly: WebResource("Wisesoft.Web.Control.Wisesoft.Calendar.calendar.js", "application/x-javascript", PerformSubstitution=true)] namespace Wisesoft.Web.Control { [ToolboxBitmap(typeof(CalenderBox), "Wisesoft.Calendar.CalendarBox.ico")] public class CalenderBox : TextBox { protected override void OnPreRender(EventArgs e) { string calendar = CalenderCSS.CSS; calendar = calendar.Replace("$ImaginURL$", this.ImaginURL); if (!Page.ClientScript.IsClientScriptBlockRegistered("_calendar")) Page.ClientScript.RegisterClientScriptBlock(typeof(string), "_calendar", calendar); this.Page.PreRenderComplete += new EventHandler(Page_PreRenderComplete); this.CssClass = "Wdate"; this.Attributes.Add("onfocus","setday(this)"); this.Attributes.Add("onchange", "checkDate(this.value)"); base.OnPreRender(e); } void Page_PreRenderComplete(object sender, EventArgs e) { Page.ClientScript.RegisterClientScriptResource(this.GetType(), "Wisesoft.Web.Control.Wisesoft.Calendar.calendar.js"); } /**//// <summary> /// 弹出日期控件小图片的地址 /// </summary> [Bindable(true)] [Category("图标设置")] [DefaultValue("imagin/calender.gif")] [Localizable(true)] public string ImaginURL { get { String s = (String)ViewState["ImaginURL"]; return ((s == null) ? "imagin/calender.gif" : s); } set { ViewState["ImaginURL"] = value; } } /**//// <summary> /// 设置日期,时间的初始格式。 /// </summary> [Bindable(true)] [Category("初始化设置")] [DefaultValue(false)] [Localizable(true)] public bool ShowTime { get { bool s = (bool)ViewState["ShowTime"]; if (ViewState["ShowTime"] != null) { return s; } return false; } set { ViewState["ShowTime"] = value; } } /**//// <summary> /// 注样式文件 /// </summary> /// <param name="path"></param> private void RegisterCssFile(string path) { HtmlLink link1 = new HtmlLink(); link1.Attributes["type"] = "text/css"; link1.Attributes["rel"] = "stylesheet"; link1.Attributes["href"] = path; this.Page.Header.Controls.Add(link1); } } } 注意:[assembly: WebResource("Wisesoft.Web.Control.Wisesoft.Calendar.calendar.js", "application/x-javascript", PerformSubstitution=true)]是用来封装你的JS文件,要使用你项目的名字加上你JS文件的名字,还需要将你的JS文件做一点设置,点右件,选择属性--->然后选择高级,选择生成操作-->选择嵌入的资源,这样才能将JS文件封装进去,当然如果有图片或者是CSS文件也是一样的。 再看 void Page_PreRenderComplete(object sender, EventArgs e) { Page.ClientScript.RegisterClientScriptResource(this.GetType(), "Wisesoft.Web.Control.Wisesoft.Calendar.calendar.js"); } 是在页面呈现之前将你的JS文件注册到页面上。 [Bindable(true)] [Category("图标设置")] [DefaultValue("imagin/calender.gif")] [Localizable(true)] 是利用反射的元数据信息,来设置属性。就是给你的日期控件旁边加上个小图标,把它做成一个属性,可以让程序员自定义设置图片,也可以把它继承进去。 好了,这样就可以把JS文件封装好了,再来看看CSS文件如何封装并写入客户端。 我们可以看见下面有一个方法, /**//// <summary> /// 注样式文件 /// </summary> /// <param name="path"></param> private void RegisterCssFile(string path) { HtmlLink link1 = new HtmlLink(); link1.Attributes["type"] = "text/css"; link1.Attributes["rel"] = "stylesheet"; link1.Attributes["href"] = path; this.Page.Header.Controls.Add(link1); }它就是用来注册你的CSS文件的,大家都知道在我们的页面代码里面是<link href="StyleSheet.css" rel="stylesheet" type="text/css" />引入外部样式文件。这个方法就是达到这个目的。那么我们现在还没有样式文件。 因此我们就必须建立一个CSS,然后把它设置一下(和JS的设置方式一样)。再到void Page_PreRenderComplete(object sender, EventArgs e)方法调用就可以了,但是还有其他方法,我们来介绍第二种(对JS文件也可以这样使用),建立一个CalendarCSS.cs文件,代码如下: using System; using System.Collections.Generic; using System.Text; namespace Wisesoft.Web.Control { public class CalenderCSS { public static string CSS = @"<style type=""text/css""> .Wdate{ border:#999 1px solid; height:18px; background:url($ImaginURL$) no-repeat right; } .WdateFmtErr{ font-weight:bold; color:red; } </style>"; } }这个类其实是将我们的CSS文件,写为一个字符串形式,然后供主函数调用,以注册到客户端使用。 那么我们再看看CalendarBox.cs文件里的这段代码 string calendar = CalenderCSS.CSS; calendar = calendar.Replace("$ImaginURL$", this.ImaginURL); if (!Page.ClientScript.IsClientScriptBlockRegistered("_calendar")) Page.ClientScript.RegisterClientScriptBlock(typeof(string), "_calendar", calendar); 它就是将我们已经写好的一段字符串以快的形式注册到客户端(当然还有更多的注册方式,可以在MSDN看看ClientScript类)。 好了,基本上就可以使用了。编译一下呢?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值