Programming in asp.net-mvc: ASP.NET – Why is my cookie not persisted? on newest questions tagged asp.net-mvc – Stack Overflow

i’m trying to set a cookie to store a selected department in. The cookie is set with a small form which has a select-dropdown with departments. This is posted using AJAX.

This is how I store the cookie:

<AcceptVerbs(HttpVerbs.Post)> _
Function ChangeDepartment(ByVal FormValues As FormCollection) As ActionResult
    If Response.Cookies("department") IsNot Nothing Then
        Response.Cookies("department").Value = FormValues("department")
    Else
        Dim c As New HttpCookie("department")
        c.Value = FormValues("department")
        c.Expires = Now.AddDays(7)
        Response.Cookies.Add(c)
    End If

    Return Json(New With {.newDepartment = Response.Cookies("department").Value})
End Function

The .newDepartment variable is returned correctly with the correct value.

This is how I retrieve the cookie and build the select-dropdown:

<% Ajax.BeginRouteForm("ChangeDepartment", New AjaxOptions With {.LoadingElementId = "loading", .HttpMethod = "post", .OnSuccess = "function(request) {ajaxMessage('Department change', 'Department changed to: ' + request.get_response().get_object().newDepartment);}"})%>
    <select name="department">
        <option>Default</option>
        <option<%If Request.Cookies("department") Isnot Nothing andAlso Request.Cookies("department").Value = "Supervisor" Then Response.Write (" selected=""selected""") %>>Supervisor</option>
        <option<%If Request.Cookies("department") Isnot Nothing andAlso Request.Cookies("department").Value = "Purchasing" Then Response.Write (" selected=""selected""") %>>Purchasing</option>
        <option<%If Request.Cookies("department") Isnot Nothing andAlso Request.Cookies("department").Value = "Engineering" Then Response.Write (" selected=""selected""") %>>Engineering</option>
    </select>
    <input type="submit" value="Change department" />
<% Html.EndForm%>

The cookie isn’t stored, because the select-dropdown keeps going back to Default. Am I doing something wrong?

See Answers


source: http://stackoverflow.com/questions/1086303/asp-net-why-is-my-cookie-not-persisted
Programming in asp.net-mvc: programming-in-asp-net-mvc



online applications demo