0

In PHP I can define and use a function like this:

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

If I try to do the same thing in C#, using the <% %> syntax, it will always throw an error. It doesn't like having the extra text/html showing up in the function.

Can someone show me how to write the above example in C#? I am unable to find the terms that will yield a result in Google

4

3 回答 3

0

解决方案:感谢@joel-coehoorn 和如何在 cshtml 模板中创建函数?

<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>
于 2013-06-12T13:41:13.340 回答
0

创建一个 *.cshtml 文件,并使用Razor View Engine。它支持您正在寻找的那种混乱的语法。

于 2013-06-11T19:46:05.430 回答
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的组合符合您的喜好。

于 2013-06-11T19:49:59.647 回答