Search code examples
c#javascripthtmlasp.netencoding

How to stop asp.net encoding characters before outputing to html?


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 (&#39;)

How can I avoid this and make ' appear in the html?


Solution

  • 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