ASP.NET页面传值

方法1使用状态试图:ViewState

有效期等于页面的生命周期,仅服务器控件可用(runat=”server”)。

 

ViewState是用于在页面提交自身的情况下保存页面数据状态的一个对象。

本质:页面上的一个叫做__ViewState<input type=“hidden”的隐藏域标签。

 

 

语法:

ViewState["nameid"] = TextBox1.Text;//存储信息

TextBox2.Text= ViewState["nameid"].ToString();//读取信息

 

 

使用例子:

protected void Button1_Click(object sender, EventArgs e)

{

     ViewState["textbox"] = TextBox1.Text;

}

protected void Button2_Click(object sender, EventArgs e)

{

      TextBox2.Text= ViewState["textbox"].ToString();

}

在page指令中加入EnableViewState="false",可禁止整个页面的ViewState

 

 

使用注意:

ViewState虽然使用方便,但是谨慎使用,因为使用过多,会大幅度降低应用程序的性能(速度)。

 

 

方法2:使用隐藏控件传值

<input type="text" id="text1" runat="server"  visible="false"  />

 

 页数数据传递

IsPostBack介绍

IsPostBack是Page类有一个bool类型的属性,用来判断针对当前Form的请求是第一次还是非第一次请求。当IsPostBack=true时表示非第一次

点击按钮就不是第2次访问了

protected void Page_Load(object sender, EventArgs e)

{

        if (this.IsPostBack)

        {

              Response.Write("<script>alert('我不是第一次访问!')</script>");

         }

         else

         {

              Response.Write("<script>alert('我是第Ì一次访问!')</script>");

         }

}

 

 

 

 

 

  面传值的实现原理图

 

 

跨页面传值例子:

页面a.aspx

<table border="1" style="width: 58%;">

  <tr>

    <td class="style1">请输入您的姓名</td>

    <td><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>

  </tr>

  <tr>

    <td class="style1"><asp:Button ID="Button1" runat="server" Text="提交本页面" onclick="Button1_Click" /></td>

    <td><asp:Button ID="Button2" runat="server" Text="提交到b.aspx" PostBackUrl="b.aspx" /></td>

</tr>

  <tr>

     <td class="style1"><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></td>

     <td></td>

</tr>

 </table>

 

 

a.aspx.cs文件

 protected void Button1_Click(object sender, EventArgs e)

 {

      Label1.Text = "hello" + TextBox1.Text;

 }

 

 

 

 

 

页面b.aspx

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

 

 

 

b.aspx.cs代码

protected void Page_Load(object sender, EventArgs e)

{

      if(Page.PreviousPage!=null)

      {

            TextBox t1 = (TextBox)PreviousPage.FindControl("TextBox1");

            if (t1 != null)

             {

                  Label1.Text = "hello" + t1.Text;

             }

       }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值