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?

Upvotes: 8

Views: 29079

Answers (4)

Michal Nies.
Michal Nies.

Reputation: 91

You need to inject context at the top of your view:

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor context

Then you can use like this:

@{var myCookie = context.HttpContext.Request.Cookies["myCookie"]}

Depending on framework version it may also be required to register context in application (in Program.cs or Startup.cs):

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Upvotes: 0

Nerdroid
Nerdroid

Reputation: 14006

use Request.Cookies

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

Upvotes: 1

nicedev92
nicedev92

Reputation: 1705

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

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

Upvotes: 20

Nikhil Prajapati
Nikhil Prajapati

Reputation: 942

for Read Cookie:

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

and show it in view As:

    @ViewBag.MyCookie;

Upvotes: 4

Related Questions