【问题标题】:HTML code template in ASP.NET .aspxASP.NET .aspx 中的 HTML 代码模板
【发布时间】:2013-11-13 17:04:51
【问题描述】:

我希望能够利用 PHP 的强大功能在 ASP.NET 中实现代码模板。以下两个代码文件输出相同,但 PHP 更优雅,甚至可以导入到其他 PHP 文件中以便重复使用。

ASP.NET:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ASP_dot_NET_test.WebForm1" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server"><title></title></head>
<body>
<script runat="server">
    delegate void Make_buttons(int count);
</script>
<%
Make_buttons Make_buttons = i =>
    {
    for (int k = 0; k < 2; k++)
        {
        %>
        <hr />
        <button><%= "buy " + i + " candies!" %></button>
        <%
        }
    };
%>

<div>
    <%
    Make_buttons(count: 5);
    %>
</div>
</body>
</html>

PHP:

<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<?php
function Make_buttons ($i)
    {
    for ($k = 0; $k < 2; $k++)
        {
        ?>
        <hr />
        <button><?= "buy " . $i . " candies!"; ?></button>
        <?php
        }
    }
?>

<div>
    <?php
    Make_buttons(5);
    ?>
</div>
</body>
</html>

我知道母版页,但它们完成了页面模板,而不是像上面那样的代码模板。

我可以通过哪些最佳方式来实现这一目标?

【问题讨论】:

  • 不完全确定您在寻找什么,但也许背后的代码或用户控件或 Razor 部分视图有效?
  • 不是代码隐藏,因为它不能有 HTML 文字。也不是用户控件,因为我不打算创建控件。我想要 ASP.NET 中 PHP 的 HTML 预处理能力和便利性。不,使用 PHP 不是一种选择。
  • 我认为您应该查看 Razor... 在您的其他 cmets 上:“代码隐藏...不能有 HTML 文字” - 显然不是真的,因为 ASPX 页面首先转换为 C#代码/编译然后渲染; user controls 只是可重复使用的页面片段,而不是“按钮”中的“控件”。
  • 你能给我看一个包含 HTML 文字的代码隐藏示例吗?
  • 将示例添加为“答案”,因为它无法放入评论中。

标签: c# html asp.net templates


【解决方案1】:

样本(不是答案):

使用Control.RenderControl 使用控件将文字文本写入输出:

protected override void Render(HtmlTextWriter output)
{       
   output.Write("<br>Message from Control : " + Message);       
   output.Write("Showing Custom controls created in reverse" +
                                                    "order");         
}

从 ASPX 自动生成的代码:

<form id="form1" runat="server">
<div>
    Some text <%=42%> more text.

</div>
</form>

结果:

 private void @__Renderform1(
     System.Web.UI.HtmlTextWriter @__w, System.Web.UI.Control parameterContainer) 
 {
        @__w.Write("\r\n    <div>\r\n        Some text ");
      @__w.Write(42);
       @__w.Write(" more text.\r\n\r\n    </div>\r\n    ");
 }

【讨论】:

    【解决方案2】:

    我不知道如何在 .aspx 中做到这一点。如果您愿意切换到 Razor 模板...您可以使用帮助语法,如...

    @helper SayHello(string name)
    {
        <div>Hello @name</div>
    }
    
    @SayHello("John")
    

    您可以通过创建魔法目录“App_Code”并将您共享的 cshtml 文件放入其中来跨多个文件共享帮助程序。

    http://www.asp.net/web-pages/overview/ui-layouts-and-themes/creating-and-using-a-helper-in-an-aspnet-web-pages-site

    Move common razor helpers to another file

    How do I define a method in Razor?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-24
      • 2015-01-18
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 2015-02-10
      相关资源
      最近更新 更多