在MVC控制器中检索Cookie

时间:2015-07-08 07:43:40

标签: javascript asp.net-mvc cookies

我创建了一个在document.ready

下触发的JavaScript函数
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

当我尝试从MVC控制器中检索此cookie时...

HttpContext.Request.Cookies["cname"].Value 

我得到一个空值并显示错误。我如何获得此cookie的价值?

更新代码。不知道为什么它会突然发挥作用。我不记得我改变了任何代码。

<script type="text/javascript" language="javascript">
$(document).ready(function () {
        setCookie('cname','computername',999);

});

控制器

var computername=HttpContext.Request.Cookies["cname"].Value

脚本文件

function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;

}

1 个答案:

答案 0 :(得分:1)

您的代码运行正常,但我认为您忘记在javascript

内的视图中编写scripts section代码
@section scripts
{
   <script>
       $(document).ready(function () {
           setCookie("test", "test", 10);
       });

       function setCookie(cname, cvalue, exdays) {
           var d = new Date();
           d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
           var expires = "expires=" + d.toUTCString();
           document.cookie = cname + "=" + cvalue + "; " + expires;
       }
</script> 
}