如何获取cookie中的值

时间:2014-12-26 07:34:40

标签: c# asp.net-mvc-4 cookies

我有以下代码

var s = Request.Cookies["myvalue"].Value;
string[] values = s.Split(',').Select(x => x.Trim()).ToArray();

这是Jquery

$(document).ready(function () {
    $("#btnAddToCart").click(function () {
        $(this).css("background-color", "green");
        if (typeof $.cookie('myvalue') == 'undefined') {
            $.cookie("myvalue", 0, { expiry: 1 });
        }            
        var a = $(".img1").attr("id");          
        var imgsrc = $.cookie("myvalue").split(",");
        var count = 0;
        var totalitems = 0;
        for (var i = 0; i < imgsrc.length; i++) {                             
            if (a == imgsrc[i]) {
                break;
            }
            else {
                count++;
            }
        }
        var lenghtOfArry = imgsrc.length;
        if (count >= lenghtOfArry) {
            $.cookie("myvalue", $.cookie("myvalue") + "," + a, { expiry: 10 });
        }
        else {
            alert('This value already exist');
        }
        for (var i = 0; i < imgsrc.length; i++) {
            totalitems++;
        }
        $(".para").text("CART" + " " + "(" + totalitems + ")");
        $(".para").css("color", "#fff");
        $(".para").css("text-align", "center");
    });
});

当我尝试访问cookie值时调试它的值为

0%2C40%2C50%2C60%2C80%2C9

我希望值为

0 4 5 6 8 9

怎么做?

1 个答案:

答案 0 :(得分:1)

您的Cookie值似乎是网址编码。请尝试以下方法:

var s = Request.Cookies["myvalue"].Value;
s = HttpUtility.UrlDecode(s ?? string.Empty);
string[] values = s.Split(',').Select(x => x.Trim()).ToArray();