我有一个按钮和一个文本框。我想在文本框中输入一个值,当我单击按钮时,页面将重新加载,但该值仍应位于文本框中。我该怎么做。以下代码不起作用
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (ViewState["value"] != null)
{
TextBox1.Text = ViewState["value"].ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["value"] = TextBox1.Text;
Response.Redirect("default.aspx");
}
}
}
Response.Redirect按照它所说的去做 - 将请求重定向到新页面。视图状态永远不会被应用。如果需要重定向,请考虑改用会话。
如果您不需要重定向,只需不要重定向并仅更新需要更新的页面部分。
Viewstate只能保留该值,直到您在同一页面上。您正在重定向到其他页面。因此,不使用视图状态使用会话。
asp.net Web表单已经在页面刷新时保持了视图状态。 不需要任何代码来处理此操作。
看到这个 : http://www.w3schools.com/aspnet/showaspx.asp?filename=demo_aspnetviewstate
转自 : http://www.w3schools.com/aspnet/aspnet_viewstate.asp
并查看此讨论
试试这个
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (ViewState["value"] != null)
{
TextBox1.Text = Session["value"].ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["value"] = TextBox1.Text;
Response.Redirect("default.aspx");
}
}
}
由于您正在重定向到新的视图,因此视图状态将没有任何帮助。所以,使用会话
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["value"] != null)
{
TextBox1.Text = Session["value"].ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["value"] = TextBox1.Text;
Response.Redirect("default.aspx");
}
}
}