Skip to content Skip to sidebar Skip to footer

How To Stop Asp.net Encoding Characters Before Outputing To Html?

I have a function that generates a javascript code for me. hello c# code protected String getOnCilckJS(

Solution 1:

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.

Solution 2:

You're using <%: %>, which actually does encode the value. You're looking for <%= %>.

See also Diference between special tags asp.net.

Solution 3:

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:

<%: newHtmlString(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:

<scripttype="text/javascript">var array = ["<%: new HtmlString(string.Join(@""",""", stringArray)) %>"];
</script>

Normally, the double quote characters are html encoded and converted as &quot; 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!

Solution 4:

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><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title></title></head><body><formid="form1"runat="server"><div>          
        **<imgsrc="abc.png"alt="hello"onclick="<%= getOnCilckJS(11)  %>" />**
    </div></form></body></html>

Server side

**protectedstringgetOnCilckJS(int arg)**
        {
            if (arg == 1)
            {
                return"alert('hello world');";
            }
            else
            {
                return"alert('hello universe');";
            }
        }

I got the alert message without any single quote

Post a Comment for "How To Stop Asp.net Encoding Characters Before Outputing To Html?"