Declare a class in inline-code in aspx/c#

2019-08-23 05:10发布

I've got a self contained aspx script that now needs a small class for one function. Is there any way to declare a class in the code of this page without adding a code behind (aspx.cs) file?

I'd like to keep everything in one single file for neatness sake.

标签: c# asp.net class
3条回答
Luminary・发光体
2楼-- · 2019-08-23 05:28

I'd like to keep everything in one single file for neatness sake. I fail to see how mixing code and markup could ever be neat. That being said, you could add the class inside of a <script> block, e.g: -

<script runat="server">
  public class MyClass
  {
     public static string Example()
     {
        Response.Write("Hello world");
     }
  }
</script>
查看更多
欢心
3楼-- · 2019-08-23 05:28

The most straightforward way is something like this:

<%@ Page Language="C#"%>

<script runat="server">
  public string OneFunction(string input)
  {
    return "It worked" + input;
  }
</script>
查看更多
我命由我不由天
4楼-- · 2019-08-23 05:28

Yes, they are called Embedded Code Blocks, like this:

<%@ Page Language="C#" %>
<script runat=server>
protected String GetTime()
{
    return DateTime.Now.ToString("t");
}
</script>
<html>
<body>
   <form id="form1" runat="server">
       Current server time is <% =GetTime()%>.
   </form>
</body>
</html>
查看更多
登录 后发表回答