简体   繁体   English

在Global.asax.cs中设置cookie,并在asp.net mvc c#视图中获取它

[英]Set cookie in Global.asax.cs and get it in the view of asp.net mvc c#

I registered cookie in session start of Global.asax.cs of asp.net mvc project. 我在asp.net mvc项目的Global.asax.cs的会话开始中注册了cookie。 And then I want to test the variable of the cookie in the View. 然后,我想在View中测试Cookie的变量。

Global.asax.cs : Global.asax.cs:

HttpCookie instock = new HttpCookie("instockV");
instock.Value = "1";
Response.Cookies.Add(instock);

In my view, I'm using jquery : 在我看来,我正在使用jquery:

<div id="test"></div>
$("#test").text($.cookie("instockV"));

But the result in my div is null . 但是我的div中的结果为null

Anyone know about this issue please share. 任何人都知道此问题,请分享。

Thanks. 谢谢。

Did you add the plugin of jquery cookie? 您是否添加了jQuery cookie插件? never the less if you don't have it, to read the cookie the code it's with pure javascript it's easy do it like this 如果您没有它,就更是如此,要使用纯JavaScript读取cookie的代码,就很容易做到这一点

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

UPDATE 更新

Tried in you Global.asax the append like this 在Global.asax中尝试了这种附件

HttpCookie instock = new HttpCookie("instockV");
instock.Value = "1";
Response.AppendCookie(instock);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在ASP.NET MVC C#中使用Jquery更新部分视图 - Updating partial view with Jquery in ASP.NET MVC C# 带有部分视图的AJAX MVC 4 ASP.net C# - AJAX with partial view MVC 4 ASP.net C# elFinder-asp.net连接器global.asax配置 - elFinder - asp.net connector global.asax configuration 局部视图部分(但不是完全)与JQuery一起使用C#ASP.Net MVC 5 - Partial View Works with JQuery Partially, But Not Completely C# ASP.Net MVC 5 Asp.Net MVC:基于JSON或C#类对象数据生成动态视图 - Asp.Net MVC: Generate dynamic view based on JSON OR C# class object data 如何使用jquery或ajax在c#/asp.net中为MVC项目更新razor局部视图 - How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project 在ASP.NET MVC视图页面中使用C#生成javascript是否正确? - Is it right to generate the javascript using C# in ASP.NET MVC view page? 在ASP.NET MVC C#中从控制器向视图显示结果 - Display result from controller to the view in asp.net mvc c# 如何在 ASP.NET MVC 中过滤 C# 数据表 查看关于更改 select 框选项更改 - How to filter a C# DataTable in a ASP.NET MVC View on change of a select box option change 无法在 ASP.NET MVC-C# 的级联下拉列表中获取 Chil 表列表 - Unable to Get Chil Table List in Cascading Dropdown list in ASP.NET MVC- C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM