Delay when reading data from viewstate

冷暖自知 提交于 2020-01-16 19:21:33

问题


So i am trying to save a variable in the viewstate and use right after the button is pressed. The problem is that you have to press a botton 2 times before something is written. This code is the problem as i see it boilde down to the basics.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
    <body>
        <form id="form1" runat="server">
            <asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button1_Click" />
            <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button 2" />
        </form>
    </body>
</html>

in the code behind using System;

public partial class _Default:System.Web.UI.Page {

    protected void Page_Load(object sender, EventArgs e) {
        Response.Write(ViewState["Button"]);
    }

    protected void Button1_Click(object sender, EventArgs e) {
        ViewState["Button"] = "Button 1";
    }

    protected void Button2_Click(object sender, EventArgs e) {
        ViewState["Button"] = "Button 2";
   }
}

回答1:


Your page load event occur before your button click events so in first page load you view state is blank.

On first button click it is still blank because page load is call first then your button click.

Now on second time button click view state have value so it will show on your page

Here you have to use page Pre Render event to show view state values like following

protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            Response.Write(ViewState["Button"]);
        }

Put this in you page class and it will work in single button click



来源:https://stackoverflow.com/questions/20370662/delay-when-reading-data-from-viewstate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!