2012-02-21 80 views
1

我希望使用C#和Razor語法檢查cookie是否已設置。如果已定,我想表明根據變量的值呈現不同的HTML

<h2> Cookie set </h2>. 

如果還沒有,我想顯示

<h2>Cookie not set</h2> 

因此,審查了一些東西,我有這樣的設置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); 

使用Razor,語法上,最好的方法是什麼來呈現我所希望的?無論我嘗試結果編譯錯誤:

@{ 
    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> 

@} 

顯然這是可怕的看起來,它不起作用。它確實顯示了我想要的功能。如何實現此功能的最佳方式?

回答

1

如果你的if語句的邏輯是比單襯不再允許,你可以設置一個代碼塊的變量:

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

然後你的剃鬚刀代碼可能看起來像這樣:

@if (isCookieSet) { 
    <h2>Cookie set</h2> 
} else { 
    <h2>Cookie not set</h2> 
} 
0

你可以嘗試像

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

只要記住要小心邏輯e用戶界面(即視圖)。

您不妨考慮一下編輯視圖模型,包括cookie的值,並根據該變量使用一個簡單IF語句顯示不同的UI:

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

然後該控制器具有閱讀該cookie,並設置視圖模型屬性:

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

的這個優點是:

  • 根據此值,控制器可能需要「啓用功能」或執行其他邏輯
  • 測試:測試UI元素很困難。易於測試視圖模型。