asp.net-mvc 如何在视图 MVC3 中读取 cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18651213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:09:15  来源:igfitidea点击:

How to read cookie in view MVC3?

asp.net-mvcasp.net-mvc-3cookies

提问by Nguy?n Tr?ng B?ng

I have a list of comment objects in the view. Each comment has one cookie that mark the status from user action. Example: like, spam,...

我在视图中有一个评论对象列表。每条评论都有一个 cookie,用于标记用户操作的状态。例如:喜欢,垃圾邮件,...

In the view, I want to read the corresponding cookie of each comment to display the right view to user. Example: user A who liked comment B then the view will display the unlike button

在视图中,我想读取每个评论的相应cookie,以向用户显示正确的视图。示例:用户 A 喜欢评论 B 然后视图将显示不同按钮

I don't want to read cookie in the controller because the return data is a list of comment objects.

我不想在控制器中读取 cookie,因为返回数据是一个注释对象列表。

My question is how to read cookie directly in view of MVC3?

我的问题是如何针对MVC3直接读取cookie?

回答by nicedev80

In razor view within @{ } block use below code.

在 @{} 块内的剃刀视图中使用下面的代码。

string val = "";
if (Request.Cookies["CookieName"] != null) {
    val = Request.Cookies["CookieName"].Value;        
}

回答by Nikhil Prajapati

for Read Cookie:

对于读取 Cookie:

    var cookie = Request.Cookies["Key"];
    ViewBag.MyCookie= int.Parse(cookie);

and show it in view As:

并将其显示在视图中:

    @ViewBag.MyCookie;

回答by Nerdroid

use Request.Cookies

Request.Cookies

string val = Request.Cookies["CookieName"]?.Value;

string val = Request.Cookies["CookieName"]?.Value;