Search code examples
c#asp.netinline-code

Method doesn't exist if declared in the page


I have a page defined as:

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

<head>
<title>Untitled 1</title>
<script type="text/c#">
    public void WriteHello()
    {
        Response.Write("HELLO EVERYBODY");
    }
</script>
</head>
<body>
    <div>
        <% WriteHello(); %>
    </div>
</body>
</html>

But this throws the compilation error of:

The name 'WriteHello' does not exist in the current context

If I move the C# code to a seperate file, and link to it, it works as expected. But for this I need to keep it in the same file. Can you not call inline methods like this? Or am I missing something very obvious?


Solution

  • The script tag you have coded is a client side script - it will try to execute on the browser. The code that tries to use it runs on the server.

    You need to change the script to be server side script:

    <script runat="server">
    

    You can write this as:

    <%
        public void WriteHello()
        {
            Response.Write("HELLO EVERYBODY");
        }
    %>
    

    Which is the syntax you used elsewhere already.