How to stop asp.net encoding characters before out

2019-08-20 05:02发布

问题:

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?

回答1:

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



回答2:

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.



回答3:

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

See also Diference between special tags asp.net.



回答4:

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 &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!