通过维持Web表单中的对象的ViewState你可能会省去不少编码工作。


维持ViewState

在传统ASP中,当一个表单被提交的时候所有表单值都被清除。假设你提交了一个有很多信息的表单并且服务器返回一个错误。你不得不返回到表单并更正信息。你点击返回按钮,但是发生了什么……。所有表单值被清除了,你将不得不从头开始!站点没有维持你的ViewState.

在ASP .NET中提交一个表单的时候,表单与所有的表单值一起再现于浏览器窗口。怎么会这样?这是因为ASP .NET维持你的ViewState。ViewState指明页面被提交到服务器时的状态。该状态是通过在每个带有<form runat="server">控件的页面中安置一个隐含域来定义的。源文件可能看起来象是这样:

ASP .NET维持ViewState
<form name="_ctl0" method="post" action="page.aspx" >
<input type="hidden" name="__VIEWSTATE"
value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />
.....some code
</form>


对ASP.NET Web表单维持ViewState是默认设置。 如果你想要维持ViewState,可以在.aspx页面顶部包含指示:<%@ Page EnableViewState="false" %>,或者对任何控件加入属性:EnableViewState="false"。

请看下面的.aspx文件。它演示了“老方式“的做法。当你点击提交按钮,表单值将会消失:

ASP .NET维持ViewState<html>
ASP .NET维持ViewState
<body>
ASP .NET维持ViewState
<form action="demo_classicasp.aspx" method="post">
ASP .NET维持ViewStateYour name: 
<input type="text" name="fname" size="20">
ASP .NET维持ViewState
<input type="submit" value="Submit">
ASP .NET维持ViewState
</form>
ASP .NET维持ViewState
<%
ASP .NET维持ViewStatedim fname
ASP .NET维持ViewStatefname
=Request.Form("fname")
ASP .NET维持ViewStateIf fname
<>"" Then
ASP .NET维持ViewStateResponse.Write(
"Hello " & fname & "!")
ASP .NET维持ViewStateEnd If
ASP .NET维持ViewState
%>
ASP .NET维持ViewState
</body>
ASP .NET维持ViewState
</html>
ASP .NET维持ViewState

这是新的ASP .NET方式。当你点击提交按钮的时候,表单值将消失:

ASP .NET维持ViewState
<script runat="server">
Sub submit(sender As Object, e As EventArgs)
lbl1.Text="Hello " & txt1.Text & "!"
End Sub
</script>
<html>
<body>
<form runat="server">
Your name: <asp:TextBox  />
<asp:Button OnClick="submit" Text="Submit" runat="server" />
<p><asp:Label  /></p>
</form>
</body>
</html>

(在浏览器中选择查看源文件,会看到ASP .NET已经在表单中添加了一个隐含域来维持ViewState)。

相关文章:

  • 2022-03-09
  • 2022-12-23
  • 2021-06-01
  • 2021-12-29
  • 2021-10-09
  • 2021-11-15
  • 2022-12-23
  • 2021-10-16
猜你喜欢
  • 2022-12-23
  • 2021-07-13
  • 2021-08-29
  • 2021-08-08
  • 2021-06-24
  • 2021-07-08
相关资源
相似解决方案