问题
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