1

I wish to use C# and Razor syntax to check if a cookie has been set. If it has been set, I want to show

<h2> Cookie set </h2>.

If it hasn't, I want to display

<h2>Cookie not set</h2>

So, to review a few things, I have this setting the cookie :

//set cookie
HttpCookie cookie = Request.Cookies.Get("stackOverflowCookie");
if(cookie == null) {
   cookie = new HttpCookie("stackOverflowCookie");
   cookie.Value = "Hi guys!";
   cookie.Expires = DateTime.Now.AddDays(1);
   Response.Cookies.Add(cookie);

Using Razor, what is the best way, syntactically, to render what I wish? Whatever I try results in compilation errors :

@{
     if(Request.Cookies["stackOverflowCookie"] == null){ 
        //some other logic is here in my actual code, so an inline statement is not sufficient
        <h2> Cookie set </h2>
@}
@{ else {

<h2> Cookie not set </h2>

@}

Obviously this is horrible looking, and it doesn't work. It does show the functionality I would like those. How is the best way to achieve this functionality?

3 Answers 3

1

If your if statement logic is longer than a single-liner allows, you can just set a variable in a code block:

@{
    var isCookieSet = Request.Cookies["stackOverflowCookie"] == null && otherConditions;
}

And then your razor code could just look like this:

@if (isCookieSet) { 
    <h2>Cookie set</h2>
} else {
    <h2>Cookie not set</h2>
}
Sign up to request clarification or add additional context in comments.

Comments

1

Just remember to be careful of putting logic in the user-interface (ie, the View).

You may wish to consider editing the View-Model to include a value of the cookie, and display the different UI depending on this variable using a simply IF statement:

@if(model.CookieProperty != null) {
  <h2>Cookie is set</h2>
} else {
  <h2>Cookie is not set</h2>
}

And then having the controller reading the cookie, and setting the View-Model property:

model.CookieProperty = Request.Cookies["cookieName"];

The advantages of this are:

  • The controller may need to "enable functionality" or perform other logic depending on this value
  • Testing: It's difficult to test UI elements. Easy to test a View-Model.

Comments

0

You could try something like

@if(Request.Cookies["stackOverflowCookie"] == null) { 
    <h2> Cookie set </h2>
} else {
    <h2> Cookie not set </h2>
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.