Simon Kiely
Simon Kiely

Reputation: 6050

Rendering different HTML depending on value of variable

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?

Upvotes: 1

Views: 979

Answers (3)

NathanS
NathanS

Reputation: 110

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.

Upvotes: 1

Jacob
Jacob

Reputation: 78840

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>
}

Upvotes: 1

marcind
marcind

Reputation: 53183

You could try something like

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

Upvotes: 0

Related Questions