简体   繁体   中英

Reading a multiple value cookie in .net code from js cookie

I am having a terrible time trying to figure this out and searching is not coming up with any good results.

I created a cookie in my page with Jquery like so

var cookieData = {
                tb1Relation: $("#<%= tb1Relation.ClientID %>").val(),
                tb2Fname: $("#<%= tb2Fname.ClientID %>").val()
            }
            $.cookie("Relation", $.param(cookieData));

But when i get to codebehind, i can see that cookie but the values are not separated because its encoded, so it treats it like one value instead of multiple. So:

Request.Cookies("Relation")("tb1Relation")

shows as Nothing

and the Request.Cookies("Relation").Value = "tb1Relation%3Dsomething%26tb2Fname%3Dsomethingelse"

From what i can tell its because the cookies are urlencoded but i cant figure out how to unencode them for that Request.Cookies object.

My last case scenario is to the following, but its awful and i really want to avoid this.

Request.Cookies("Relation").Value = HttpUtility.UrlDecode(Request.Cookies("Relation").Value)

    Dim cookiesSplit() As String = Request.Cookies("formData2").Value.Split("&")

    'Splits the first array entry into id/val - Really lame though
    Dim cookieIdVal() As String = cookiesSplit(0).Split("=")

Any better solutions that I am completely missing?

Edit: fixed some code because I looked like I was pointing to the wrong thing. Should make more sense now

Maybe this will help... I had to read a cookie back into a textbox in codebehind, but the cookie text looked similar to your "test1%3Dsomething%26test2%3Dsomethingelse", so I had to UrlDecode

private void CheckForCookieText()
{
    string ConclusionText = SystemCookies.getSingleCookie("txtRecommended", "");
    txtRecommended.Text = (ConclusionText.Trim().Length > 0) ? HttpUtility.UrlDecode(ConclusionText) : "";
}

So after much investigation, I found that I had to add:

$.cookie.raw = true;

just before creating the cookie and now I am able to access the cookie the normal way in code

Request.Cookies("CookieName")("cookieKey")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM