Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<script runat="server"> vs <% %>

I'm here learning ASP.NET which is why I'm obviously here asking a question. So when I run a statement inside of <% %> delimiters everything works fine. I try to instead run it in a <script runat="server"> and it doesn't work. I'm just curious to what is so significant different between the two methods. I am suppose to be using the script method, but it only works with the <% %>.

My example is this... basic standard form getting "userInput" (a number) from the POST method.

        <form action="calcprime.aspx" method="post">
            Enter a number between 1-999: 
            <input type="text" name="userInput" maxlength="3" />
            <input type="submit" name="submit" value="Submit" />
        </form>

Then if I need to convert the string into an integer to do math on it I would do this...

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

<script runat="server">
    int num = int.Parse(Request.Form["userInput"]);
</script>

<%=num%>    // <-should display the number in theory..(in my head)

Unfortunately the above code errors and does not work for me, However the alternative using only <% %> using the same exact method of code works 100% fine. Such as below...

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

<%
    int num = int.Parse(Request.Form["userInput"]);
    Response.Write(num);    //displays the number as it should.. 100% working
%>

So my question is. Why doesn't the script way work? Isn't it the same thing? What is the correct way to handle this basic scenario in ASP.NET using C#? Is my approach even practical, or is there a standard that I should be aware of? The number will have math done to it, which is why I need it converted to an integer. This is just a somewhat basic foundational stuff here that I feel I should know the correct way to go about it before learning bad practices.

like image 970
Corey Avatar asked Feb 17 '15 23:02

Corey


People also ask

What is script runat server?

The RUNAT=SERVER attribute tells the Web server to process the script on the server. If you do not set this attribute, the script is processed by the client browser.

What is runat server in ASPX?

The runat="server" tag in ASP.NET allows the ability to convert/treat most any HTML element as a server-side control that you can manipulate via code at generation time. Some controls have explicit implementations, others simply revert to a generic control implementation.

What is runat server in C#?

Runat='Server ' Indicates the accessibility of the control at Serverside. Let Me make you more clear about it. If you puts runat="server" inside any of the control then you can use that control at the server side. e.g. XML.

What are the HTML server controls?

The HTML server controls are HTML elements that include a runat=server attribute. The HTML server controls have the same HTML output and the same properties as their corresponding HTML tags. In addition, HTML server controls provide automatic state management and server-side events.


2 Answers

<script runat="server">
    int num = 1;
</script>

<%=num%>

That works fine on my machine. I see the 1 on my page.

However, this doesn't work:

<script runat="server">
    int num = int.Parse(Request.Form["userInput"]);
</script>

<%=num%>  

I get this error:

CS0120: An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Request.get'

I suspect you got that error too, but didn't include it in your question. NOTE if you get an error in your code, include it in your question. Don't assume we know you got an error.

This works, assuming I add query string appropriately to the request URL:

<script runat="server">
    int num = int.Parse(HttpContext.Current.Request.QueryString["randomnum"].ToString());
</script>

<%=num%>  

I suspect this will work too, assuming you've already posted form values to the page. However, your question was not complete, so I don't know if you did it or not. That just goes to show, you need to submit a Minimal, Verifiable, and Complete example.

<script runat="server">
    int num = int.Parse(HttpContext.Current.Request.Form["userInput"]);
</script>

<%=num%>

In the end however, you probably shouldn't be doing code blocks inline (whether using a script tag or inline expression) on your page. That's better handled on code behind. <% %> stuff is fine in some contexts, but you should usually only use it to inject a value onto the page, for example when you're eval'ing something in a repeater. And if you find yourself doing a lot of those inline expressions, you might consider switching to ASP.NET MVC or Web Pages. Both of those use the Razor view engine, which is much cleaner.

like image 125
mason Avatar answered Sep 20 '22 13:09

mason


Your .aspx files are converted into .cs files (i.e. pure C#) by the behind-the-scenes ASP.NET compiler (separate from the C# compiler in the IDE). You can see these temporary .cs files if you locate your "Temporary ASP.NET Files" folder on your computer.

The class in these .cs files has a big function called Render which is what outputs to the response stream (using Response.Write). All of the static HTML in your .aspx file is converted into a String instance and fed directly into Response.Write.

<% %> blocks are converted into inline C# code that breaks-up these massive String instances inside the Render function.

<script runat="server"> blocks are instead pasted as class members in this runtime-generated class.

<asp:Foo runat="server"> elements are converted into Control instantiation and render calls.

So this:

<%@ Page Inherits="ParentPageClass" %>
<html>
<head>
    <script runat="server">
    String DoSomething() {
        return "lulz";
    }
    </script>
</head>
<body>
    <% int x = 5; %>
    <%= x %>
    <div>
        <asp:Button runat="server" />
    </div>
</body>
</html>

Is converted into this:

(I have simplified this example by removing the extra tracing calls. The #line text are special preprocessor instructions so the YSOD system can map runtime errors back to your .aspx file).

namespace ASP {

    [System.Runtime.CompilerServices.CompilerGlobalScopeAttribute()]
    public class webform1_aspx : ParentPageClass, System.Web.SessionState.IRequiresSessionState, System.Web.IHttpHandler {

        String DoSomething() {
            return "lulz";
        }

        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        private global::System.Web.UI.WebControls.HyperLink @__BuildControl__control2() {
            global::System.Web.UI.WebControls.HyperLink @__ctrl;


            @__ctrl = new global::System.Web.UI.WebControls.HyperLink();

            @__ctrl.ApplyStyleSheetSkin(this);

            @__ctrl.Text = "WebControls are evil";
        }

        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        private void @__BuildControlTree(webform1_aspx @__ctrl) {

            this.InitializeCulture();

            global::System.Web.UI.WebControls.HyperLink @__ctrl1;

            @__ctrl1 = this.@__BuildControl__control2();

            System.Web.UI.IParserAccessor @__parser = ((System.Web.UI.IParserAccessor)(@__ctrl));

            @__parser.AddParsedSubObject(@__ctrl1);

            @__ctrl.SetRenderMethodDelegate(new System.Web.UI.RenderMethod(this.@__Render__control1));
        }

        private void @__Render__control1(System.Web.UI.HtmlTextWriter @__w, System.Web.UI.Control parameterContainer) {

            @__w.Write("\r\n    </head>\r\n    <body>\r\n        ");


            #line 11 "c:\users\dai\documents\visual studio 2013\Projects\WebApplication1\WebApplication1\WebForm1.aspx"
            int x = 5; 

            #line default
            #line hidden

            #line 12 "c:\users\dai\documents\visual studio 2013\Projects\WebApplication1\WebApplication1\WebForm1.aspx"
            @__w.Write( x );


            #line default
            #line hidden

            @__w.Write("\r\n        <div>\r\n            ");

            parameterContainer.Controls[0].RenderControl(@__w);

            @__w.Write("\r\n        </div>\r\n    </body>\r\n    </html>");
        }
    }
}
like image 36
Dai Avatar answered Sep 19 '22 13:09

Dai