Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read cookie in view MVC3?

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,...

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

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

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

like image 396
Nguyễn Trọng Bằng Avatar asked Sep 06 '13 06:09

Nguyễn Trọng Bằng


3 Answers

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

string val = "";
if (Request.Cookies["CookieName"] != null) {
    val = Request.Cookies["CookieName"].Value;        
}
like image 134
nicedev80 Avatar answered Oct 22 '22 02:10

nicedev80


for Read Cookie:

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

and show it in view As:

    @ViewBag.MyCookie;
like image 41
Nikhil Prajapati Avatar answered Oct 22 '22 03:10

Nikhil Prajapati


use Request.Cookies

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

like image 23
Nerdroid Avatar answered Oct 22 '22 03:10

Nerdroid