NDIrishman23
NDIrishman23

Reputation: 33

aspx.vb cookie value accessing and updating

I am coding an ASP application where a users data will be stored in a cookie(that expires in 24 hours) and when the program is run, it is supposed to search that cookie, and add whatever was in the cookie to the current users value, then proceed through the code.

Dim I As Integer  ' iterator for cookie search
        Dim foundcookie As Boolean = False ' flag if cookie found
    Dim stakenow As Integer ' current stake held here
    stakenow = stake.Text
    Dim currentname As String
    currentname = name.Text
    For I = 0 To Request.Cookies.Count - 1
        If Request.Cookies.Item(I).Name = currentname Then
            foundcookie = True
            stakenow = stakenow + Request.Cookies.Item(I).Value
            currentstake.Text = currentstake.Text + stakenow.ToString
            Request.Cookies.Item(I).Value = stakenow.ToString
            Request.Cookies.Item(I).Expires = DateTime.Now.AddHours(24)
        End If
    Next
    If Not foundcookie Then
        Dim nameCookie As New HttpCookie(currentname)
        nameCookie.Value = stakenow.ToString
        nameCookie.Expires = DateTime.Now.AddHours(24)
        Response.Cookies.Add(nameCookie)
        currentstake.Text = currentstake.Text + stakenow.ToString
    End If

This code works, the first time, it creates a cookie with a value, say 150. Then the next time the code is run and the users "stake" that they entered was 150 again, the current stake updates to 300. However the 3rd time run, if the user enters 100, we would want the users stake now to be 400, however is is only 250. I see this error is coming from the updated value not being correctly written back to the cookie, thus the addition only coming from the original value when the cookie was created, and the typed value. I have tried using request and response cookies and have had no luck. Any suggestions?

Upvotes: 1

Views: 1221

Answers (1)

NoAlias
NoAlias

Reputation: 9193

Use the HttpCookieCollection.Set Method so that the updated cookie gets back to the client:

If Request.Cookies.Item(I).Name = currentname Then

    foundcookie = True
    stakenow = stakenow + Request.Cookies.Item(I).Value
    currentstake.Text = currentstake.Text + stakenow.ToString

    Dim objCookie As HttpCookie = Request.Cookies.Item(I)

    objCookie.Value = stakenow.ToString()
    objCookie.Expires = DateTime.Now.AddHours(24)

    HttpContext.Current.Response.Cookies.Set(objCookie)

End If

Upvotes: 1

Related Questions