简体   繁体   中英

HTML code template in ASP.NET .aspx

I want to be able to achieve code templating in ASP.NET, with the power of PHP. The following two code files result in the same output, but the PHP one is more elegant, and can even be imported into other PHP files so it can be reused.

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>

I know about Master Pages, but they accomplish page templating, not code templating like above.

What are some of the best ways I can accomplish this?

Samples (not an answer):

Writing literal text to output with Controls using Control.RenderControl :

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

Auto-generated code from ASPX:

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

</div>
</form>

results in:

 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    ");
 }

I don't know how to do that in .aspx. If you are willing to switch to Razor templates...You can use helper syntax, as in...

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

@SayHello("John")

You can share a helper across multiple files by making the magic directory "App_Code" and placing your shared cshtml files in there.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM