2012-01-19 37 views
0

在ASP.NET MVC aspx頁我有以下的腳本的字符串變量:得到的Request.RawUrl成<腳本類型= 「文本/ C#」>

<script type="text/c#" runat="server"> 
    string rl = Request.RawUrl; 
</script> 

Request在Visual有下劃線工作室有以下錯誤: 非靜態方法,字段或屬性的對象引用是必需的System.Web.UI.Page.Request.get

但是,此:<%=Request.RawUrl%>工作正常。

你能告訴我怎樣才能讓RawUrl進入腳本中的rl字符串變量嗎?謝謝!

這是How to make a variable on an aspx page visible to multiple content sections on that page in ASP.NET MVC?

我基本上我想聲明的頁面上的對象,並提到它在頁面的不同部分的延續。

回答

4

就像是:

<% 
    string rl = Request.RawUrl; 
%> 

或你的具體情況:

<script type="text/C#" runat="server"> 
    string rl = HttpContext.Current.Request.RawUrl; 
</script> 

UPDATE:

根據您的評論你想使用這個變量來自世界各地。在這種情況下,我建議你寫一個自定義的助手,這將是可訪問的所有觀點:

public static class HtmlExtensions 
{ 
    public static string GetSomeValue(this HtmlHelper htmlHelper) 
    { 
     var context = htmlHelper.ViewContext.RequestContext.HttpContext; 
     var value = context.Items["__some_key__"] as string; 
     if (value != null) 
     { 
      // the value was found in the HTTP context => no need 
      // to recalculate it 
      return value; 
     } 

     value = ... do some expensive calculation to fetch the value 
     // store the value in the HTTP context so that the next time 
     // someone calls this helper from within the current HTTP context 
     // doesn't need to perform the expensive operation 
     context.Items["__some_key__"] = value; 
     return value; 
    } 
} 

,然後當你需要的地方的值:

<%= Html.GetSomeValue() %> 
+0

但RL變量將不可見頁面上的其他腳本。這是這個問題的延續,你回答了一會兒:http://stackoverflow.com/questions/8737593/how-to-make-a-variable-on-an-aspx-page-visible-to-multiple -content-sections-on-t – Barka

+0

@ user277498,編寫一個自定義助手來返回這個值。不要在ASP.NET MVC視圖中使用這樣的全局變量。這只是錯誤的。我會更新我的答案來舉例說明。 –

+0

謝謝!我需要使用Facebook Open Graph和我自己的東西填充一些meta標籤。對於他們每個人我都在計算內容。例如,有常規描述元標記和FB描述元標記以及常規標題標記和FB標題標記等等。所有這些的計算都將原始URL作爲參數,我試圖不多次運行相同的計算。所以我想把所有這些放在一個對象中,並根據需要在頁面上訪問它們。 – Barka

相關問題