ViewState/StateBag?

  • Thread starter Thread starter Arpan
  • Start date Start date
A

Arpan

Consider the following code snippet:

<script runat="server">
Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs)
If Not (Page.IsPostBack) Then
MsgBox(1)
ViewState("StartTime") = DateTime.Now
lblMessage.Text = "The time now is " &
ViewState("StartTime") & "<br><br>"
Else
MsgBox(2)
If (CStr(Session("dtDateTime")) <> "") Then
lblMessage.Text = "<br>Your last visit: " &
Session("dtDateTime") & "<br><br>"
End If
End If
End Sub

Sub btn_Click(ByVal obj As Object, ByVal ea As EventArgs)
Dim dtDateTime As DateTime

dtDateTime = DateTime.Now
Session("dtDateTime") = dtDateTime
lblMessage.Text += "Current date time: " & dtDateTime &
"<br>Your first visit: " & ViewState("StartTime")
End Sub
</script>
<html>
<body>
<form runat="server">
<asp:Button id="submit" Text="SUBMIT" OnClick="btn_Click"
runat="server"/><br><br>
<asp:Label id="lblMessage" runat="server"/>
</form>
</body>
</html>

When the page loads for the first time, the If condition within the
Page_Load sub gets executed (the MsgBox 1 also pops up)........that's
fine but next when I click the Submit button, as expected, MsgBox 2
pops up but at the same time, the Label also shows

"The time now is " & ViewState("StartTime") & "<br><br>"

which exists in the If condition in the Page_Load sub i.e. the page
looks like

----------------
The time now is (whatever is the ViewState("StartTime") value)

Current date time: (whatever is the current datetime)
Your first visit: (whatever is the ViewState("StartTime") value)
--------------

But if the If condition under the Else condition in the Page_Load sub
is commented & the Submit button is clicked for the first time, the
page looks like this:

--------------
Your last visit:

Current date time: (whatever is the current datetime)
Your first visit: (whatever is the ViewState("StartTime") value)
--------------

Why this difference in output when the If condition under the Else
condition in the Page_Load sub is commented?

Thanks,

Arpan
 
If MsgBox call is calling Windows Forms MessageBox, you have wrong way to go
about it since MsgBox is meant for Windows Forms application. not
server-side applications, where this MsgBox would be shown at the server.
FYI: http://forums.asp.net/thread/1348589.aspx (where MsgBox was used and it
also prompted as if If's had no effect), also:
http://www.syncfusion.com/faq/aspnet/search/577.aspx

I also understand that might be using this purely for testing, so therefore
replace them with something like Response.Write(1) and Response.Write(2)
 
Back
Top