从独立的.aspx页面调用服务器端类

问题描述 投票:0回答:1

我有一个生成独立aspx页面的应用程序,这些页面在c#中有自己的script

现在我不想将所有c#脚本代码添加到c#script标记中,所以我想调用一个后端c#类,它将包含所有脚本代码(这是正常的c#代码)。我想从这个脚本中调用后端c#类,即

<script language="CS" runat="server"> 
MyClass myclass = new MyClass();// backend class
myclass.GetAllScripts(); //say this is the fucntion which contains scripting 
code
</script>
c# asp.net asp.net-mvc
1个回答
1
投票

您可以将生成的代码保存在App_Code文件夹中,此文件夹中的代码将在运行时编译并准备好应用程序的其他部分

Ef。:

var generatedCode = 
@"
    namespace MyProject
    {
        public class MyClass
        {
            public void GetAllScripts()
            {
                // ...
            }
        }
    }
";
var generatedPage = 
@"
    <%@ Page Language=""C#"" AutoEventWireup=""true"" %>
    <html>
    <head>
        <title>Test</title>
        <script language=""CS"" runat=""server"" >
            void Page_Load(object sender, EventArgs e)
            {
                //below code will be executed when the page is opened
                MyClass myclass = new MyClass();// backend class
                myclass.GetAllScripts();
            }
        </script>
    </head>
    <body>
        ...
    </body>
    </html>
";

// change to the path and file name to fit your need, but the cs file must in ~/App_Code
var aspxPath = Path.Combine(Server.MapPath("~"), "GeneratedPage.aspx");
System.IO.File.WriteAllText(aspxPath, generatedPage);

var csPath = Path.Combine(Server.MapPath("~/App_Code"), "MyClass.cs");
System.IO.File.WriteAllText(csPath, generatedCode);
© www.soinside.com 2019 - 2024. All rights reserved.