我创建了一个在document.ready
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;
}
答案 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>
}