C# HtmlEncode, then Javascript insert using .innerHTML
What follows is a piece of text that gets HtmlEncoded in C# before being sent to the browser (during a callback). Once received, in Javascript I do myDiv.innerHTML = theStringBelow
;
<span xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
xmlns:SharePoint="Microsoft.Sharepoint.WebControls"
xmlns:ext="my_namespace:my_xslt开发者_运维技巧_extension">Some text to be shown.</span>
However, what results is that I simply see the exact text shown above. It isn't being treated as an html element that got added to the DOM, but as plain text. When I add the exact same text through javascript (e.g., I skip the callback, and just say myDiv="exactString
") it DOES get added correctly (it gets treated as a span).
What is going on? Do I have to un-encode it? Should I not have encoded to begin with?
Edit The question still stands for curiosity's sake, but I have fixed the issue simply by not HtmlEncoding the data. An earlier issue must have added onto this one, making me think the HtmlEncoding was still necessary.
You should not HTMLEncode
it if it is to become HTML nodes. What HTML encoding will do is turn your string from above into this:
<span xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
xmlns:SharePoint="Microsoft.Sharepoint.WebControls"
xmlns:ext="my_namespace:my_xslt_extension">Some text to be shown.</span>
Try passing the string in as it is. You will of course have to escape the string. But once it has become a string in JavaScript it should be unescaped as it is being made into a string in memory. Then you should be able to do the div.innerHTML
call and get your expected result. The escaping of the string can probably be accomplished by doing the following:
// in your .cs code-behind/view/whatever.
string = string.replace("""", "\""");
Which should produce:
<span xmlns:asp=\"http://schemas.microsoft.com/ASPNET/20\"
xmlns:SharePoint=\"Microsoft.Sharepoint.WebControls\"
xmlns:ext=\"my_namespace:my_xslt_extension\">Some text to be shown.</span>
Which you can then output like so:
// in your webform/view
<script type="text/javascript">
var mystring;
mystring = "<%=string;%>";
</script>
Let me know how that works out for you.
HTML Encode will turn <
into <
and so on. This breaks HTML Formatting and is used so blocks of text like this:
Insert <name> here
Does not turn out like this:
Insert here
If your intent is to have the <span ...
get inserted into the html directly you either need to NOT encode it on the way out, or if that will disrupt transmission, you need to decode it in js before you set the .innerHTML
part.
精彩评论