asp.net实用的一些代码

来源:互联网 发布:软件需求管理办法 编辑:程序博客网 时间:2024/05/21 17:17


如何用Response.Redirect方法传递汉字 :
页面1:String str=Server.UrlEncode("dddddd");
            Response.Redirect("页面2?msg="+str);
页面2:String str=Server.UrlDecode(Request.QueryString["msg"]);
--------------------------------------------------------------------
如何处理多页面重定向到同一页面后的返回问题 :
页面1:Response.Redirect(页面2);
页面2:方法1:Button2.Attributes.Add("onclick","history.go(-1);return false;");
      方法2:private void Button1_Click(object sender, System.EventArgs e)
        {
            Response.Write("<script>history.go(-2);</script>");
        }
-----------------------------------------------------------------------------------------------------------------------------
IsStartupScriptRegistered("函数名")和IsClientScriptBlockRegistered("函数名")   :用于标志关键字为函数名的脚本块是否已添加的页面中
-------------------------------------------------------------------------------
<body onload="closeit()">
<script language="JavaScript">
function closeit() {
setTimeout("self.close()",3)}
</script>
------------------------------------------------------------------
onbeforeunload="return ' 真的转向啊'">
function closeIt()
{
if(event.clientX>document.body.clientWidth&&event.clientY<0||event.altKey)
{alert('我要退出啦!')}
else
{return false;}
}
----------------------------------------------------------------------------------------
<script>
if (document.all("hidd").value !="")
{
alert(document.all("hidd").value);
document.all("hidd").value="";
window.parent.location="index.aspx";
}
</script>
加在</form>
----------------------------------------------
../文件名
-------------------------------------
target="_parent"//子窗体从父窗体打开

function confirmDelete (frm)
{
for (i=0; i<frm.length; i++)
{
if (frm.elements[i].name.indexOf('CheckBox1') !=-1)
{
if(frm.elements[i].checked)
{
return confirm ('您是否要删除选择的记录?');
}
}
    }
}
<BODY onUnload="window.alert('一路走好')"><br>
--------------------------------------------------------------------------------------------------------------
<object id="id" ruant=server latebing=true/flase class="class name" || progid="com progid" || classid="com classid">
   /id属性用来设置所建立的com或.net对象的唯一名称
/class属性用来指定您要根据哪一个.net framework类来建立.net对象.
/progid属性用来指定您据以建立的com组件的程序控制识别码.
/classid属性用来指定你据以建立的com组件的类识别码
/latebinding属性指示是否要将后期绑定的api用于T1bimp.exe已处理过的com组件.
  ★-class,progid,classid属性是彼此互斥,不能同时存在一个服务器端对象标记中
DataTable d=new DataTable();  d.Columns.Add("fsdf3");  DataRow t=d.NewRow();  t[0]=45645;d.Rows.Add(t);

<meta http-equiv="refresh" content="10;url=top.aspx">自动刷新

ImageButton1.Attributes.Add("onclick","javascript:window.open('test.aspx');return false;");
//禁止网页刷新
Response.Write("<script>parent.document.frames['topIndex'].location.href='top.aspx'</script>");

using System.Web.Security;
加密 密码!~
FormsAuthentication.HashPasswordForStoringInConfigFile(Text,"MD5")

---------------------------自定义控件-------------------------------------------------------------
Control:定义由所有 ASP.NET 服务器控件共享的属性、方法和事件。

<%@ Register Tagprefix="LoginControl" TagName="Login" Src="WebUserControl1.ascx" %>
Tagprefix :决定用户控件的唯一的命令空间。TagName:用户控件的唯一名称。
---------------读取xml---------------------------------
DataSet ds=new DataSet();
ds.ReadXml(Server.MapPath("客户.xml"));
System.Data.DataView dv=new DataView(ds.Tables["客户"]);
DataGrid1.DataSource=dv;
DataGrid1.DataBind();
---------------------------------------
用户资料保存于web.config时
private void butlogin_Click(object sender, System.EventArgs e)
{
   if(FormsAuthentication.Authenticate(boxid.Text,boxpd.Text))
     FormsAuthentication.RedirectFromLoginPage(boxid.Text,false);
   else
     Response.Write("error");

---------------------------------------------
cookie-----------------------------------------------------------------
HttpCookie MyCookie;
MyCookie = Request.Cookies["UserLayout"];//获得客服端发送的Cookie的集合
HttpCookie MyCookie = new HttpCookie("UserLayout");
MyCookie.Values.Add("ForeColor","rty");// 设定 Cookie 中各项目(索引键) 的值
MyCookie.Expires = DateTime.MaxValue;// 设定 Cookie 永远不会过期
Response.AppendCookie(MyCookie);
// DateTime dt = DateTime.Now;
// TimeSpan ts = new TimeSpan(0, 0, 10, 0);
// MyCookie.Expires = dt.Add(ts);
------------------datagrid中得到行--------------------------------------------------------------------------
private void DataList1_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
{if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem) || (e.Item.ItemType == ListItemType.SelectedItem) || (e.Item.ItemType == ListItemType.EditItem))
{System.Data.Common.DbDataRecord drv = (System.Data.Common.DbDataRecord)e.Item.DataItem;
     if (Convert.ToInt32(drv["min_lvl"]) > 60)
e.Item.BackColor = Color.Red;}}

private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
//foreach(DataGridItem i in this.DataGrid1.Items)
//{i.Cells[2].Attributes.Add("onmouseover","this.style.background='red'");
//i.Cells[2].Attributes.Add("onmouseout","this.style.background='white'");}
e.Item.Attributes.Add("onmouseover","this.style.background='red'");
e.Item.Attributes.Add("onmouseout","this.style.background='white'");}
代理:
this.DataGrid1.ItemDataBound+= new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
onmouseover="this.style.background='red'" onmouseout="this.style.background='blue
-------------------javascript----------------------------------------------------
Response.Write(@"<script language=javascript>alert('请输入正确信息!')</script>");
Page.RegisterStartupScript("Startup",@"<script>alert('gfhfh!')</script>");
    alert("确定");
    document.write("谢谢!");
    if(confirm("是否要关闭当前窗口?")) {window.close();}
数字型 (Number)
逻辑型或布尔型 (Boolean)
字符串型(String)
空型 (null)
eval 函数
isNaN 函数
onClick  onChange  onFocus  onBlur  onMouseOver onMouseOut  onLoad  onSubmit  onMouseDown  onMouseUp
text事件: onFocus="接受焦点处理例程; "  onBlur="失去焦点处理例程; "  onChange="改变内容处理例程; "
●得到单选按钮var the_box = window.document.form_1.radio_1;
        if (the_box.checked == true){
             window.document.form_1.radio_2.checked = false
●组合框与列表框事件onFocus  onBlur  onChange
function show(txt)
{
  alert("选中的是"+ txt);
}
<select name="choose_category"   
onChange="show(the_form.choose_category.options[selectedIndex].text);">
 <option selected>狗</option>
 <option>鱼</option>
 <option>鸟</option>
</select>
Window 对象  属性document   event   history   location    name   screen 
             方法alert   blur   close    focus   navigate   open
Document 对象表示给定浏览器窗口中的 HTML 文档,用于检索有关该文档的信息。 
         属性alinkColor bgColor body fgColor linkColor location title URL vlinkColor  
         方法clear   close     open     write   writeln 
History对象  方法 back  forward   go
Location 此对象包含有关当前 URL 的信息,它提供了重新加载窗口的当前 URL 的方法。
         属性hash   host   hostname   href 
         方法assign   reload   replace

-------------------连接数据库-----------------------------------------------------------
DataBinder 类 :提供对 RAD 设计器的支持,以生成和分析数据绑定表达式语法
SqlConnection 表示 SQL Server 数据库的一个打开的连接。不能继承此类。
                ("server=.;uid=sa;pwd=;database=pubs")
SqlCommand: 表示要对 SQL Server 数据库执行的一个 Transact-SQL 语句或存储过程。
            CommandTimeout 属性: 获取或设置在终止执行命令的尝试并生成错误之前的等待时间。
            CommandText 属性: 获取或设置要对数据源执行的 Transact-SQL 语句或存储过程。
            CommandType 属性: 获取或设置一个值,该值指示如何解释 CommandText 属性.
                        取值: StoredProcedure 存储过程
            Parameters  集合

SqlDataReader 类:  提供一种从数据库读取只进的行流的一种方式。不能继承此类。
           -CommandBehavior 枚举:  提供对查询结果和查询对数据库的影响的说明
            --成员: SingleRow  查询应返回一行。执行查询可能会影响数据库状态。一些 .NET Framework 数据提供程序可能(但不要求)使用此信息
                    来优化命令的性能。在用 OleDbCommand 对象的 ExecuteReader 方法指定 SingleRow 时,用于 OLE DB 的 .NET Framework 数据提
                    供程序使用 OLE DB IRow 接口(如果可用)执行绑定。否则,它使用 IRowset 接口。如果您的 SQL 语句应该只返回一行,
                    则指定 SingleRow 还可以提高应用程序性能.在执行返回多个结果集的查询时,可以指定 SingleRow。在这种情况下,仍返回多个结果集,
                    但每个结果集只有一行。

SqlDataAdapter 类 :表示用于填充 DataSet 和更新 SQL Server 数据库的一组数据命令和一个数据库连接.
                   SqlDataAdapter 与 SqlConnection 和 SqlCommand 一起使用,以便在连接到 Microsoft SQL Server 数据库时提高性能。
绑定: sql ★方法一:    用sqlDataAdapter连接
                    this.sqlDataAdapter1.Fill(dataSet11);
              this.DataGrid1.DataBind();
          ★方法二:    用sqlConnection连接---先sqlConnection(设置ConnectionString连),再SqlCommand(设置Connection);
            写代码 this.sqlConnection1.Open();
SqlDataReader dr=this.sqlCommand1.ExecuteReader();//ExecuteReader将CommandText发送到Connection并生成一个 SqlDataReader。
DataGrid1.DataSource=dr;
DataGrid1.DataBind();
dr.Close();
this.sqlConnection1.Close();
数据对象与界面工具更新实际演练  ★方法一:  用sqlConnection连接

●用sqlCommand连接:
MyCommand.Parameters.Add("@name",SqlDbType.NVarChar,20);
MyCommand.Parameters["@name"].Value=name.Text;
●用sqlDataAdapter连接:
MyCommand.Parameters.Add(new SqlPArameter("@name",SqlDbType.NVarChar,20));
MyCommand.Parameters["@name"].Value=name.Text;
DataSet ds=new DataSet();
DataView dv;
dataView 表示用于排序、筛选、搜索、编辑和导航的 DataTable 的可绑定数据的自定义视图
      dv =ds.Tables["Table-name"].DefaultView;
----------------------控件-------------------------------------------------------------------------------------------------
●RadioButton 控件 :控件组GroupName ;
●CustomValidator 控件 :计算输入控件的值以确定它是否通过自定义的验证逻辑。
●Label :标记 说明
        <a> 将内部文本转换为超级链接。超级链接文本不能包含其他格式标记。
        <b> 将内部文本转换为粗体样式。
        <br> 换行。
        <i> 将内部文本转换为斜体样式。
        <p> 开始新段落;或者,在与结束标记一起使用时,将内部文本放置于单独的段落中。
●Literal 控件: 在 Web 页上保留显示静态文本的位置。(位置:可将控件加至Panel容器中)
  Literal 控件与 Label 控件类似,但 Literal 控件不允许对所显示的文本应用样式。可以通过设置 Text 属性,以编程方式控制在控件中显示的文本。
●TextBox 控件 :TextMode属性 文本框行为模式(Password 密码).  Wrap 属性 自动换行. MaxLength 属性 限制输入的字符数(TextMode设为MultiLine无效).
                ReadOnlys属性 是否只读. 
●CheckBoxList 控件: selected 属性 设置起始勾选状态.
●DataGrid 控件 :AutoGenerateColumns属性设为true,表示它会自动替数据源中的每一个字段创建BoundColumn对象。
                 AutoGenerateColumns属性设为false,html--<Columns>标记之间列出想要内含的字段。
                 --DataField 设置要绑定至BoundColumn的字段。
                 --DataFormatString 设置列中项的显示格式。
                 --FooterText 设置要显示于列页脚节中的文本。
                 --HeaderImageUrl 设置图,此图会取代HeaderText.
                 --HeaderText 设置要显示于列页眉节中的文本。
                 --ReadOnly 设置是否可以编辑列中的项。
                 --SortExpreession 在选取列来排序时,要传递至OnSortCommand方法的字段或表达名称。(DataField)
                 --Visible 设置列是否会显示于DataGrid服务器控件中。
                 --FooterStyle-property 设置列页脚节的样式属性。
                 --HeaderStyle-property 设置列页眉节的样式属性。
                 --ItemStyle-property 设置列中项的样式属性。
                 <ItemStyle BackColor="#ccffff"></ItemStyle>项目风格
●HyperLink 控件 :显示到其他 Web 页的链接的控件。
-------样式-------------------------------------------------------------------------------------------------------------
DataGrid服务器控件:样式对象属性的优先顺序.1.EditItemStyle 2.SelectedItrmStyle 3.AlternatingItemStyle 4.ItemStyle 5.ControlStyle
<LINK REL="stylesheet" TYPE="text/css" HREF="MyStyles.css">

----------------------函数----------------------------------------------------------------------------------------------
Convert.ToSingle 方法 :将指定的值转换为单精度浮点数字。
  IsPostBack 获取一个值,该值指示该页是否正为响应客户端回发而加载,或者它是否正被首次加载和访问。
String.Trim() 从此实例的开始位置和末尾移除一组指定字符的所有匹配项。

★HttpBrowserCapabilities 类 :使服务器能够收集有关在客户端运行的浏览器功能的信息。
★/当您要在运行时动态添加、移除或依次通过控件时,向页上添加 PlaceHolder Web 服务器控件。
★/Int16.Parse 方法 :将数字的字符串表示形式转换为它的等效 16 位有符号整数。
★LiteralControl类 :表示 HTML 元素、文本和 ASP.NET 页中不需要在服务器上处理的任何其他字符串。
★UnitType枚举 :指定度量单位。(% Percentage 度量单位是父元素的相对百分比) Image1.Width=new Unit(string );

★Context 提供对整个当前上下文(包括请求对象)的访问。您可以使用此类共享页之间的信息。继承HttpContext类 ;
       ---(类名--(网页名))Context.Handler 属性 :为当前 HTTP 请求获取或设置 IHttpHandler 对象。
★网页传值:
  方法一/ WebForm1--    public string str=TextBox1.Text;
                       Server.Transfer("WebForm2.aspx");//终止当前页的执行,并为当前请求开始执行新页。
                       //Server.Execute 它将从 writer 接收的 HTML 流写入 HTTP 输出流。使用另一页执行当前请求。
         WebForm2--接收 // <%@ Reference Page="WebForm1.aspx"%>//需在WebForm2开头处加入
                        WebForm1 w;
                  w = (WebForm1)Context.Handler;  //为当前 HTTP 请求获取或设置 IHttpHandler 对象。
            this.Label1.Text = w.str;
  方法二/ WebForm1--    Session["t"]=TextBox1.Text; Response.Redirect("WebForm2.aspx");
          WebForm2--   Label1.Text=(String)Session["t"];
  方法三/ WebForm1--   Response.Redirect("WebForm2.
aspx?name="+System.Web.HttpUtility.UrlEncode(TextBox2.Text)+"&name2=");
                       //对 URL 字符串进行编码,以便实现从 Web 服务器到客户端的可靠的 HTTP 传输。
          WebForm2--   Label2.Text=Request.QueryString["name"];
  ---- HtmlEncode   //对要在浏览器中显示的字符串进行编码。
★Response.Write(Server.MapPath("/WebForm2.aspx")); //为当前请求将请求的 URL 中的虚拟路径映射到服务器上的物理路径。
★Response.BufferOutput 属性 :获取或设置一个值,该值指示是否缓冲输出,并在完成处理整个页之后将其发送。
★Response.Redirect 将客户端重定向到新的 URL
  重定向至其他网页: Response.BufferOutput=true;
          Response.Redirect("WebForm1.aspx");
------------------------------------------------------------------------------------------------------------------
可以使用服务器端 #INCLUDE 指令将一个文件包含到另一个ASP文件中。
  <! -- #include virtual | file = “filename” -- >
Virtual 关键字:用于表示 Include 文件的虚拟路径。
        <! -- #include virtual = “/MyPages/Headings.inc”-->
File 关键字:用于表示该文件的物理路径。
   <! -- #include file = “Headings.inc” - - >
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="WebApplication4.WebForm1" %>
AutoEventWireup 自动事件绑定
--------------------------------------------------------------------------------
CreateObject用于在服务器上创建ActiveX 组件的实例。然后可以使用脚本来调用该对象的方法或属性。
<HTML>
<BODY>
<%
   Set TypeofBrowser = Server.CreateObject("MSWC.BrowserType")
   TypeofBrowser = Request.ServerVariables("HTTP_USER_AGENT")
   Response.Write (TypeofBrowser)
%>
</BODY>
</HTML>
-------------------------------------------------------------------------------
  MapPath 方法由服务器用于将路径映射到服务器上的信息。
    如果虚拟目录 MyPages 的路径是 C:/Inetpub/wwwroot/MyDirectory。
      <%Response.Write Server.MapPath("/MyPages")%>
  将返回
C:/Inetpub/wwwroot/MyDirectory
-----------------------------------------------------------------------------
URLEncode 方法返回一个字符串,该串是对输入值string进行URL编码,
对于在URL中无效的所有字符,如?、&和空格,都转换为相应的URL转义符.
<%
Response.Write Server.URLEncode("http://10.1.6.150.95/Chapter3/Ch3Ex14.asp")
%>
-------------------------------------------------------------------------
ScriptTimeout属性    指定脚本在终止之前可以在服务器上运行的时间长度,单位为秒。
              Server.ScriptTimeout = Numseconds   属性的默认值为90秒
-------------------------------------------------------------------------
<%
  Application.Lock
  Application("Counter") = Application("Counter") + 1
  Application.Unlock
%>
该页面已被访问过
<%= Application("Counter") %> 次!
第一行中的Lock方法将锁定Application变量。这将确保只有当前控制该页面的用户可以访问或修改Counter变量,
访问该页面的其他用户将无法修改该变量的值。当明确调用UnLock方法,或者到达该页面结尾处时,当前的用户将失去控制权,
该控制权随后会传递给访问该页面的其他用户。
-----------------------------------------------------------   
会话会在下列情况下启动:
新用户请求 ASP 文件,且 Global.asa 文件包括Session_OnStart 过程时。
Session 变量中存储一个值时。
用户请求 ASP 文件,且 Global.asa 文件使用 <object> 标记实例化具有会话范围的对象时。
会话会在下列情况下结束:
如果用户在应用程序中未请求或者未刷新网页的 时间达到了 Timeout 属性指定的时间。此属性的 默认值为 20 分钟。
如果会话已经被放弃。
   <%
   Session("mytime") = formatdatetime(now, vblongformat)
   %>
   <%=Session("mytime")%>

SessionID属性    包含唯一的用户会话标识符。<%Response.Write(Session.SessionID)%>
.....................
LCID属性         用于设置本地标识符。它存储诸如日期、货币和时间格式之类的本地信息。
2048 美国   /   2057 英国      /1036 法国    / 3079 瑞典
<%
   Session.LCID = 1036
%>
<%
   Dim due
   due = 50
   Response.Write("今天日期为" &FormatDateTime(Date)
         & "<BR>")
   Response.Write("到期金额总计为"
         & FormatCurrency(due))
%>
..............
TimeOut 属性用于以分钟为单位指定 Session 对象在资源被释放之前可保持不活动状态的持续时间
默认超时时间 20秒        Session.Timeout=30
................
cookie

        
Request
    集合 Form         用于取得使用 POST 方法提交数据的表单中表单元素的值
                     
         QueryString  集合用于取到 HTTP 查询字符串中的变量值。
                      <a href="Ch2ex6b.asp?name=Mark&name=Twain&name=Richard"> 查询字符串可包含多个值</a>
                      <%
                      for i=1 to Request.QueryString("name").Count
                      Response.Write(Request.QueryString("name")(i) & "<br>")
                      next
                      %>
         ServerVariables   用于取得预定义环境变量的值。
         ClientCertificate         Cookies
    属性 TotalBytes   返回客户端在请求正文中发送的字节总数。
    方法 BinaryRead   用于获取作为POST请求而从客户端传送到服务器的部分数据。


Rrsponse
    集合  Cookies
    属性  Buffer      属性指定是否要缓存输出结果     <%response.Buffer=true%><html><body>
                                                    <%for i=1 to 100 response.write(i & "<br />") next%>
                                                    </body></html>                 
          CacheControl   <%response.CacheControl="Public"%>
          Charset
          Expires        <%response.Expires=1440%>
          ExpiresAbsolute       
          IsClientConnected     属性可用于确定用户是否仍连接着服务器。 <%If response.IsClientConnected=true then
                                                                         response.write("用户仍处于连接状态!")
                                                                         else
                                                                         response.write("用户已断开连接!")end if%>
    方法  AddHeader           
          AppendToLog
          BinaryWrite               
          Clear       Clear方法用于清除到目前为止缓存的输出结果。  <%for i=1 to 100  response.write(i & "<br />")next response.clear%>

          End          End 方法将停止处理脚本并将当前结果返回到浏览器。 <%for i=1 to 50  response.write(i & "<br />") nextresponse.End
                                                                        for i=51 to 100
                                                                        response.write(i & "<br />") next%>
          Flush
          Redirect    Redirect 方法可用于将用户重定向到不同的页面。  <%@ Language=VBScript %>
                      <%IF Request.Form("username") <> "Mark" Then
                      Response.Redirect "http://10.1.6.150:95/Chapter 2/Ch2Ex8.htm"
                      Else
                      Response.Redirect "http://10.1.6.150:95/Chapter 2/Ch2Ex14d.htm"End If%>
          Write          
本文转摘自『蓝派网』http://www.lan27.com/Article/200705/917_2.htm

原创粉丝点击