2017-08-02 140 views
0

我使用JavaScript設置一個cookie訪問cookie的值,當用戶點擊一個按鈕:在ASP.NET核心MVC Razor視圖

document.cookie = "menuSize=Large"; 

我需要訪問在剃刀語法此Cookie所以可以輸出每當用戶更改頁面時,在_Layout.cshtml頂部顯示正確的樣式:

@{ 
     if (cookie == "Large") 
     { 
      <style> 
LARGE STYLES 
      </style> 
     } 
     else 
     { 
      <style> 
SMALL STYLES 
      </style> 
     } 
    } 
+0

嗨,是重要的把值在cookie?爲什麼你不把它放在視圖包裏?所以你可以輕鬆訪問它。據我所知,你點擊一個按鈕,設置cookie和加載視圖,所以你有一個回傳。那麼,正如我剛剛提到的那樣,爲什麼你不把價值放在一個視圖包裏,然後用剃刀把它抓住。或者使用Request.Cookies,它會是:@ Request.Cookies –

+0

你的問題是什麼?你不知道如何訪問cookie? [Request.Cookie](https://msdn.microsoft.com/en-us/library/system.web.httprequest.cookies.aspx) – Spectarion

回答

1

您可以使用此方法獲取cookie值。同時確保您的Cookie域路徑爲root。你也可以編寫一些輔助方法來獲取C#中的cookie值。

@{ 
     if (Request.Cookies["menuSize"].Value== "Large") 
     { 
      <style> 
       LARGE STYLES 
      </style> 
     } 
     else 
     { 
      <style> 
       SMALL STYLES 
      </style> 
     } 
} 
+0

由於某些原因,intellisense無法識別Request.Cookies。我最終得到它與Context.Request一起工作。這是因爲我使用ASP.NET MVC Core? –

+0

沒有一些VS讓我們傻瓜! –

0

我不得不去頭和手動拉出我的cookie被創建/ SET上的客戶端:

//HACK ridiculous i have to do all this instead of just getting the cookie from the cookies collection 
var cookieFromHeaderString = (context.HttpContext.Request.Headers["Cookie"]).FirstOrDefault(); 

if (cookieFromHeaderString != null) 
{ 

    string[] strArray = cookieFromHeaderString.Split(new string[] { "; " }, StringSplitOptions.None); 
    string whCookie = strArray.Where(m => m.StartsWith("vpWH=")).FirstOrDefault(); 

    if (whCookie != null) 
    { 
     int start = whCookie.IndexOf("=") + 1; 
     string cookieValue = whCookie.Substring(start); 

     string[] whArray = cookieValue.Split(' '); 

     int viewportWidth = 0; 
     int viewportHeight = 0; 

     if (whArray.Length == 2) 
     { 
      int.TryParse(whArray[0], out viewportWidth); 
      int.TryParse(whArray[1], out viewportHeight); 
     } 
    } 
}