2

I'm playing around with inline code blocks in asp.net. Can somebody tell me why the following code doesn't work?

<%@ Language="C#" %>
<%
    Response.Write(TestClass.ShowMessage());

    public class TestClass
    {
        public static string ShowMessage()
        {
            return "This worked!!";
        }
    }
%>

I get the following error message: CS1513: } expected

2
  • Inline code blocks are mostly for compatibility with Classic ASP. If there's no particular reason you're playing with them, I'd suggest you skip over them and play with something more useful. Commented Jun 18, 2009 at 17:18
  • My requirements called for a quick solution that an .aspx file with inline code handled perfectly. Commented Jun 21, 2009 at 3:15

2 Answers 2

4

You’ve got the Response.Write floating there outside of a function.

Why are you not placing this code in a script tag:

<script runat="Server">
    public class TestClass
    {
        public static string ShowMessage()
        {
            return "This worked!!";
        }
    }
</script>

Then:

<%=TestClass.ShowMessage()%>

Note the <%=expr%> is handled specially.

Many consider this to be an impure approach. You could do this:

<script runat="Server">
    protected void Page_Load(object sender, EventArgs e)
    {
        litMessage = TestClass.ShowMessage();
    }
</script>
<asp:literal id="litMessage" runat="server" />
Sign up to request clarification or add additional context in comments.

1 Comment

I kind of like the second example. I think it is nice to know. Thanks.
3

I think to be able to write a whole class you need to place it inside a tag block

<script runat="server" language="C#">
//Put your class here
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.