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.
<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.
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>");
}
}
}
Related
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.
If you want to call code behind function from aspx, the class is public and the function is public static, and as long as you've imported the namespace in an <%# Import %> directive.
user server tag to call server side methods:
<body>
<% Active_Frozen(text,color); %>
</body>
How can I use C# methods to alter an Asp:TextBox item's Text value(or any other value) dynamically only from ASPX side?
I can access any C# variable using <%= .... %> to select a class for a div. But cannot use it for any Aspx item's Text property.
Here, the three aspx items fail to fetch the variable from C# part but divs are easily using that for selecting a CSS class
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="test.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="site.css" rel="stylesheet" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="testBox" runat="server" Text="<%= test.TestClass.TestMethod() %>"></asp:TextBox>
bye bye world!
</div>
<div>
<asp:TextBox ID="TextBox2" runat="server" Text='<%= test.TestClass.TestMethod() %>'></asp:TextBox>
bye bye world!
</div>
<div class="<%=test.TestClass.CustomCSSClass() %>" >hello world! </div>
<div class='<%=test.TestClass.CustomCSSClass() %>' >hello world! </div>
<div class=<%=test.TestClass.CustomCSSClass() %> >hello world! </div>
</form>
</body>
</html>
Output is:
As you can see, only divs are accepting <%= ... %> and they are styled. But Asp:TextBox items having issues and printing the C# code directly instead of the value.
Here is the CSS(not related but putting anyway):
body {
}
.CustomCSSClass {
margin-top:50px;width:300px;height:200px;background-color:red;
}
Here is the C# methods that Im testing:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace test
{
public class TestClass
{
public static string TestMethod()
{
return "ASPX and HTML and CSS";
}
public static string CustomCSSClass()
{
return "CustomCSSClass";
}
}
}
While double-quote, single-quote and even quoteless versions work for selecting a style class, aspx fails to compile for quoteless version and other two are giving wrong results.
The <%= ... %> bee stings are short hand for calling Response.Write(). In other words, their result goes directly to the output stream written to the browser. You can't assign it to the property of an ASP.Net control. ASP.Net controls are server-side controls, meaning they have properties that are processed by the server before html is generated and later written to the response stream. The two items work at different levels of abstraction, and don't really fit well together.
If you want to set the text property of a control, do it in a code-behind file, or in a server-side method in your same file. If you don't want to have a code-behind file or server-side methods, then you don't need server-controls and can just use an html input element instead.
I have a function that generates a javascript code for me.
<img src="abc.png" alt="hello" onclick="<%: getOnCilckJS(arg) %>" />
c# code
protected String getOnCilckJS(int arg)
{
if (arg==1)
{
return "alert('hello world');";
}
else
{ return "alert('hello universe');";
}
}
all works fine apart from when the page is loaded asp.net converts single quotations ' to the encoded html string (')
How can I avoid this and make ' appear in the html?
Your application is Web Forms or MVC?
If it is MVC, you can try the Html.Raw(...) function, If it is Web Forms you can check this link.
You're using <%: %>, which actually does encode the value. You're looking for <%= %>.
See also Diference between special tags asp.net.
In ASP.NET WebForms the razor syntax is invalid so the way to stop the string encoding in the output of a string is to use the HtmlString() for example the inline syntax is:
<%: new HtmlString(stringVariable) %>
Below is an example how to output a variable in JavaScript inline code on a ASP.NET WebForm page. The code sample outputs a C# string array into a JavaScript array:
<script type="text/javascript">
var array = ["<%: new HtmlString(string.Join(#""",""", stringArray)) %>"];
</script>
Normally, the double quote characters are html encoded and converted as " and breaks the JavaScript syntax - using the HtmlString() method stops the encoding.
However, as stated in previous answer to avoid using the HtmlString() simply use the appropriate special ASP.Net tag syntax to output your values - <%: %> encodes characters and <%= %> is raw output!
Review the differences between ASP.Net special tags here!
Your code working to me :
But just change <%: to <%= ( and I send the parameter myself)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="xxxx.aspx.cs" Inherits="SampleAngularApp.xxxx" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
**<img src="abc.png" alt="hello" onclick="<%= getOnCilckJS(11) %>" />**
</div>
</form>
</body>
</html>
Server side
**protected string getOnCilckJS(int arg)**
{
if (arg == 1)
{
return "alert('hello world');";
}
else
{
return "alert('hello universe');";
}
}
I got the alert message without any single quote
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?
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.
You are missing
<script runat=server type="text/c#">
You need to change it to
<script type="text/c#" runat="server">
Otherwise your code will not get compiled at runtime
i just want to be able to call a javascritp subroutine on the client, after the server has done its thing (when an action completes or control goes to the view, i'd dont mind calling the js from the view either).
for some reason, even vs2010 doesn't let me put breakpoints in <% ... %> tagged areas between <script...> and </script> tagged areas. i for this reason can't figure out whats going on and how it's running things. here is what i've put in my view, and the javascritp should run, but it doesn't....
im just trying to call "RunOnceRoutines;" but it's not getting called!
the 2 questions: how on earth do we call javascript methods from server, and where is all this lovely javascript debugging i've heard about since vs2008? no where to be found!
<%# Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl(Of FP.RatePicModel)" %>
<script type="text/javascript" language="javascript">
var RatePicPanelRunCount = 0;
function ChangeMainPic(newSrc) {
$get("imgPic").src = newSrc;
alert($get("imgPic").src + '\n' + newSrc);
RatePicPanelRunCount++;
}
function UpdateGlobalVariables() {
// Update variables...
ShownPicID = <%=Model.CurShownPicID%>;
<% //this shows up!
msgbox(model.curshownpicid)
%>
ShownUserID = <%= Model.CurShownUserID %>;
CurrentUserID = <%= UserID %>;
alert('CurUserID is ' + CurrentUserID);
alert('From cookie its ' + getCookie('UserID'));
}
function RunOnceRoutines() {
if (RatePicPanelRunCount == 0) {
ChangeMainPic('<%= Model.CurPicURL%>');
UpdateGlobalVariables;
};
}
RunOnceRoutines;
</script>
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td>
<%
Html.RenderPartial("AddToFavs", Model.AddFavAction)
%>
</td>
</tr>
</table>
Looks to me like you have syntax errors causing the js to break before it gets to that function invocation. Have you checked your debug output? The Firebug plugin for FireFox is great for this
Edit:
To enable JS debugging in ie, you need to set it in the internet explorer options. Checkout out this link for details