如何将cookie值绑定到knockout中的变量

时间:2015-01-12 06:59:49

标签: asp.net-mvc knockout.js view

我有一个烹饪名称用户,我想访问我的淘汰js脚本文件中的cookie值并将其分配给一个可观察变量。我怎么能这样做?

var Suggestion = {
    SuggestionId: self.SuggestionId,
    Title: self.Title,
    CategoryId: self.CategoryId,
    ProductId: self.ProductId,
    Details: self.Details,
    StatusId: self.StatusId,
    CreatedDate: self.CreatedDate,
    CreatedBy: self.CreatedBy,
    ModifiedDate: self.ModifiedDate,
    ModifiedBy: self.ModifiedBy,
    UserId: self.UserId

};

我想为createdby分配cookie中的值   var userCookie = new HttpCookie(“user”,user.UserName); 该怎么做

1 个答案:

答案 0 :(得分:1)

如果您的Cookie设置为HttpOnly标记,则无法从javascript访问其值。您可以检查document.cookie的值以了解您是否可以看到它。在这种情况下,一种可能的解决方案是通过服务器端脚本将cookie的值存储在某个全局javascript变量中:

<script type="text/javascript">
    @{ var cookieValue = Request.Cookies["user"] != null ? Request.Cookies["user"].Value : ""; }
    var user = @Html.Raw(Json.Encode(cookieValue));
</script>

然后在您的敲除脚本中,您可以访问此全局变量:

CreatedBy: user,