简体   繁体   中英

How can I make use of a function written in the cs file by calling it in the aspx file

Currently I have the following code in Visual Studio asp.net. It seems like I'm making a new function in the head, while I want to use the one written in the aspx.cs file. The color is not working as I intended, but I'll get back to that.

It could look something like this:

 //<script type="text/javascript" src='<%= Active_Frozen(string text, string color) %>'></script>


<head>
    <script type="text/javascript">
        function Active_Frozen(text,color) 
        {
            document.write(text,color);
        }
    </script>
</head>

<body>
    <script type="text/javascript">
        Active_Frozen(text,color);
    </script>
</body>

public Tuple<string,string> Active_Frozen(string text, string color) {
    connection();
    string query = "SELECT CustomerInfo FROM ActiveSubscription WHERE UserName=@UserName";
    SqlCommand cmd = new SqlCommand(query, conn);

    if(query=="true")
    {
        text = "Active";
        color = "Green";
    }
    else
    {
        text = "Frozen";
        color= "Red";
    }

    return Tuple.Create(text, color);
}

EDIT: The reason I have the code in my aspx.cs file is because HTML does not support string hence why it's needs to be amoung the server code. That's why I need to reach the function from the aspx file since I need the text to contain two different options.

Not that way, but you can ofcorse use that specific function in your aspx page, if you bring its implementation here (on aspx page). You can even have all the code in you aspx file. (kind of a single-file page) . You Actually want to implement Embedded Code Blocks in ASP.NET Web Pages . Here's an example:

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

But in general, using embedded code blocks for complex programming logic is not a best practice, because when the code is mixed on the page with markup, it can be difficult to debug and maintain. In addition, because the code is executed only during the page's render phase, you have substantially less flexibility than with code-behind or script-block code in scoping your code to the appropriate stage of page processing.

如果要从aspx调用函数后面的代码 ,则该类为public且该函数public static ,只要您已在<%@ Import %>指令中导入了名称空间。

user server tag to call server side methods:

<body>

   <% Active_Frozen(text,color); %>
</body>

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