2013-06-11 64 views
0

在PHP我可以定義和使用這樣的功能:寫的WebForms語法內聯函數內

<html> 
    <head></head> 
    <body> 
     <?php 
     function processItem($item) 
     { 
      $item = $item * 10; 
      ?> 
      The item is <strong><?= $item ?></strong><br /> 
      <?php 
     } 
     ?> 

     <?php 
      $items = array(1,2,3,4); 
      for($i = 0; $i < $items.length; $i++) 
      { 
       processItem($items[$i]); 
      } 
     ?> 
    </body> 
</html> 

如果我嘗試做的在C#同樣的事情,使用<% %>語法,它總是會拋出錯誤。它不喜歡在函數中顯示額外的文本/ html。

有人可以告訴我如何在C#中編寫上述示例嗎?我無法找到在Google中產生結果的條款

+0

C#通常不作爲腳本語言。 –

+0

當然可以。看到上面的http://msdn.microsoft.com/en-us/library/aa479011.aspx但我知道你必須使用aspx頁面。我不確定簡單的HTML頁面。 –

回答

0

解決方案:由於@喬爾 - coehoorn和How to create a function in a cshtml template?

<html> 
    <head></head> 
    <body> 
     @helper processItem(int item) 
     { 
      item = item * 10; 
      <text> 
      The item is <strong>@item</strong><br /> 
      </text> 
      var anotherCalculation = item + 2; 
      <strong>some more text</strong> 
     } 

     @{ 
      var items = myIntArray; 
      for(var i = 0; i < items.Count; i++) 
      { 
       processItem(items[i]); 
      } 
     } 
    </body> 
</html> 
0

創建* .cshtml文件並使用Razor View Engine。它支持你正在尋找的那種混亂的語法。

+0

你能提供一個例子嗎?我仍然認爲我完全可以從我嘗試過的所有內容中完成這項工作,並且已經閱讀 – user1886419

0

如果我正確地理解你,它看起來像你想你的代碼在你的HTML相同的網頁。這在asp.net中很簡單,有時也被稱爲「單一文件」代碼。下面是一個〔實施例:http://www.codeproject.com/Articles/8178/Inline-Single-File-vs-CodeBehind

的主要區別是,你應該把它放在插圖中head標籤:

<%@ Page Language="C#" debug="true" trace="false"%> 
<html> 
    <head> 
    <title></title> 
    <script runat="server"> 
     // ASP.NET page code goes here 
     void Page_Load() { 
     //On Page Load Run this Code 
     } 
    </script> 
    </head> 
    <body>  
    <form runat="server"> 
     <!-- ASP.NET controls go here --> 
    </form> 
    </body> 
</html> 

這並不少見很久以前,但使用asp.net web表單最喜歡的人利用文件分離並使用文件後面的代碼。

如果您是來自PHP並習慣於這種編碼風格,那麼您可能會根據自己的喜好找到這種和Razor的組合。

+0

我可以在'Page_Load()'內部放入'<% %>'代碼嗎? – user1886419

+0

您可以使用Page_Load()中的這些標籤之間的代碼,但您希望自己排除<% %>標籤。這是一個很好的網站,讓你開始使用asp.net編程:http://www.asp.net/get-started –