Reputation: 1348
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?
Upvotes: 0
Views: 5031
Reputation: 8079
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.
Upvotes: 1
Reputation: 2346
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!
Upvotes: 1
Reputation: 38663
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
Upvotes: 0
Reputation: 151588
You're using <%: %>
, which actually does encode the value. You're looking for <%= %>
.
See also Diference between special tags asp.net.
Upvotes: 1