ViewState/StateBag?

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
 
T

Teemu Keiski

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top