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
Related
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>");
}
}
}
Essentially, my issue is this: I'm trying to display a ViewData variable on an ASPX page, but I'm getting "ViewData does not exist in the current context."
What led me here? I'm new to MVC, and am following an online tutorial. In Lesson 1, he has us create a view by going to Add > View, which creates a Razor view. Then, in the next tutorial, he's teaching us to use ViewData to pass a variable to the view. But, when he displays it, he's doing so using the <%: %> method, which doesn't work on my Razor page. So, I try to create an ASPX page in my View folder by creating a Web Form the traditional way. When I do that, I get the error mentioned above. I have successfully figured out how to get the Razor method working in my cshtml page, but what is the appropriate method should I want to do it the "angle bracket - percent" way?
Edit: Basically, all I did was follow the instructions for Tutorial 2 in the following walk-through. He doesn't really explain HOW he created the ASPX page (or that he used an ASPX page at all). If anyone knows of a better tutorial that's more complete, I'm all ears.
http://www.codeproject.com/Articles/207797/Learn-MVC-Model-View-Controller-step-by-step-in#Lab1:- Creating a simple hello world ASP.NET MVC Application
Edit2: By request, here's my code:
ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MVCLearn.Views.FirstMVC.Index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%= ViewData["vwTest"] %>
</div>
</form>
</body>
</html>
And here is my Controller:
public class FirstMVCController : Controller
{
// GET: FirstMVC
public ActionResult Index()
{
ViewData["vwtest"] = "Something";
return View();
}
public ActionResult SayHello()
{
return View("HelloView");
}
}
<%= ViewData["vwTest"] %>
ViewData["vwtest"] = "Something";
vwTest != vwtest
You should write same name
<%= ViewData["vwTest"] %>
ViewData["vwTest"] = "Something";
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’m new to JavaScript. Basically I want a function in JavaScript which will show me an email preview in a web browser. I’ve stored email’s template, body and contents.
SQL:
SELECT Name, template, body, contents FROM Email
WHERE EmailID = 1
C#:
I have a LinkButton (ID="lnkViewDoc") on asp.net page and the code behind is:
lnkViewDoc.Attributes.Add("onclick", "return preview_email();");
JavaScript:
I need a function please which will pick values from the class fields and show it in a web browser. thanks
function preview_email() {
..................
window.open() //Something
}
Contents:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org
/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<center>
..................
</center>
</body>
Body:
<div style="text-align: left"> Dear .......,
...........................................
</div>
<div style="text-align: left"> </div>
Take a look at the front-end server tags (bee stings). The ones I thing you're looking for are
<%=... %>
This is basically equivalent to Response.Write().
Suppose you have a .NET object named "email".
In code behind write:
lnkViewDoc.Attributes.Add("onclick", "return preview_email(" + email.EmailID + ");");
In javascript:
function preview_email(emailid) {
..................
window.open("previewEmail.aspx?emailid=" + emailid, ... more parameters)
}
If you're not afraid of using jquery in your javascript newbie days, you can try to use Jquery Dialog like this:
$("<div></div>").load("previewEmail.ascx?emailid=5").dialog({autoOpen:true});
or something similar,
you may want to consider just opening that same dialog with a iframe linking to the aspx, because your email will contain disturbing html elements like body tags