MVC Access存储的cookie [英] MVC Access stored cookie

查看:67
本文介绍了MVC Access存储的cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个页面下拉菜单,在这里我可以选择一些货币值来显示。

I want a dropdown on a page, WHere i can select some currency value to display.

然后在任何页面上,我可以通过使用cookie 来访问所选的值。

And then, on any page, I can access the value that was selected, via the use of cookies.

但是,我似乎只能访问cookie(显示在屏幕)(如果已发布)。否则刷新页面,该页面为空白

However, I only seem able to access the cookie (Display on screen), if it was posted. Else refreshing the page, it is blank.

我在做什么错了?

Controller

Controller

public ActionResult CurrencySelection()
    {
        Response.Cookies.Add(Request.Cookies["Currency"]);
        return PartialView();
    }

    [HttpPost]
    public ActionResult CurrencySelection(String currencySelection)
    {
        HttpCookie fc = new HttpCookie("Currency", currencySelection);
        Response.Cookies.Add(fc);

        return PartialView();
    }

我的视图/助手:

@{
    String currency = Response.Cookies["Currency"].Value;

    @("CURRENCY: " + currency)    
}

  @using (Ajax.BeginForm("CurrencySelection", "Header", new AjaxOptions { UpdateTargetId = "currencySelectionDiv" }))
 {      
    <select name="currencySelection">
      <option value="GBP">GBP</option>
      <option value="DKK">DKK</option>
      <option value="SEK">SEK</option>
      <option value="EURO">EURO</option>
    </select>

    <input  type="submit" value="Update" id="submit" />   
}


推荐答案

为了读取Cookie客户端需要使用 HttpOnly 标志设置为 false 。假设您最初是在服务器端创建cookie,则您的代码将如下所示:

In order to read a cookie client-side it needs to be created with the HttpOnly flag set to false. Assuming you initially create the cookie server-side then your code would look like

HttpCookie fc = new HttpCookie("Currency", currencySelection);
fc.HttpOnly = false; // enable client-side access
Response.Cookies.Add(fc);

这意味着在您看来,无需任何服务器端交互,即可通过以下方式查询该Cookie值:使用Java脚本解析 document.cookie 属性。在解析cookie方面,在线上有大量示例,实际上,文档中提供了一个很好的小实用程序-请参阅一个小框架:具有完整Unicode支持的完整cookie读取器/写入器

This means in your view, without any server-side interaction, you can query for that cookie value by parsing document.cookie property using Javascript. In terms of parsing the cookie, there are tons of examples online, and infact, there is a good little utility supplied in the documentation - see A little framework: a complete cookies reader/writer with full unicode support

这篇关于MVC Access存储的cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆