I'm receiving JSON data from an ASP.NET web service that has been HtmlEncoded with Microsoft's AntiXSS library (Encoder.HtmlEncode()
) and then returned as JSON via a jQuery Ajax call.
I am populating edit form inputs with this data like so: $('descriptionTextBox').val(object.Description);
Other times, I may just be appending it as Html to the page which displays the data as expected: $('descriptionSpan').html(object.Description);
Obviously, this resulted in the form inputs displaying encoded data if the string originally contained Html or characters that were encoded. To decode the data for display in inputs, I am using the following:
function decodeHtml(encodedStr) {
return $("<div/>").html(encodedStr).text();
}
like so $('descriptionTextBox').val(decodeHtml(object.Description));
Is this the proper way encoded data should be set on forms/inputs with JavaScript?
Yes, I think that's fine. For an alternative way to decode strings containing html entities please take a look at this answer: https://stackoverflow.com/a/9609450/240324.
I personally like this method more, because it doesn't creates an html element just to decode a string, however it's nothing wrong with your method.