2014-09-26 121 views
5

當我的視圖加載時,我需要檢查用戶正在訪問哪個域,並根據結果引用不同的樣式表和圖像源出現在頁面上。錯誤CS0103:名稱''在當前上下文中不存在

這是我的代碼:

@{ 
    string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"]; 

    if (currentstore == "www.mydomain.com") 
    { 
     <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" /> 
     string imgsrc="/content/images/uploaded/store1_logo.jpg"; 
    } 
    else 
    { 
     <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" /> 
     string imgsrc="/content/images/uploaded/store2_logo.gif"; 
    } 
} 

然後,還有更遠我叫IMGSRC變量是這樣的:

<a href="@Url.RouteUrl("HomePage")" class="logo"><img alt="" src="@imgsrc"></a> 

我得到一個錯誤說:

錯誤CS0103:名稱'imgsrc'在當前上下文中不存在

我想這是因爲「imgsrc」變量是在一個現在已關閉的代碼塊中定義的......?

在頁面下方引用此變量的正確方法是什麼?

回答

6

只需將聲明移至if塊之外即可。

@{ 
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"]; 
string imgsrc=""; 
if (currentstore == "www.mydomain.com") 
    { 
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" /> 
    imgsrc="/content/images/uploaded/store1_logo.jpg"; 
    } 
else 
    { 
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" /> 
    imgsrc="/content/images/uploaded/store2_logo.gif"; 
    } 
} 

<a href="@Url.RouteUrl("HomePage")" class="logo"><img alt="" src="@imgsrc"></a> 

你可以讓它更清潔。

@{ 
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"]; 
string imgsrc="/content/images/uploaded/store2_logo.gif"; 
if (currentstore == "www.mydomain.com") 
    { 
    <link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" /> 
    imgsrc="/content/images/uploaded/store1_logo.jpg"; 
    } 
else 
    { 
    <link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" /> 
    } 
} 
相關問題