javascriptxmlasp.net-mvcdymo

Javascript converts XML characters to &LT and &GT


I am currently using DYMO Label Printing software to print labels. I have previously had the label XML template stored as plain text and it worked fine. But recently I have decided to move to a more dynamic approach so that labels can be edited and modified directly from the database.

So I am currently storing the XML label templates in a simple SQL database table. I set up the viewmodel that contains the XML information, and then access it in Javascript when printing in the View itself.

I previously just tried this:

        try {

            var labelXml = "@Viewmodel.XMLString"; //Open XML from Viewmodel directly
            var labelD = dymo.label.framework.openLabelXml(labelXml);                        
        }
        catch(err) {
            alert("Couldn't load label");
            return;
        }

And that did not work.

I did some research and also tried this (placing viewmodel in "text/plain") and then accessing it above.

    <script>
           try {

            var labelXml = $('#label_XML').text();
            var labelD = dymo.label.framework.openLabelXml(labelXml);                             
        }
        catch(err) {
            alert("Couldn't load label");
            return;
        }     
   

</script>

<script id="label_XML" type="text/plain">
    @Viewmodel.XML
</script>

Both of these methods result in this: (<> replaced with &lt and &gt) XML rendered in Source

How can I simply access a XML string in the database from the viewmodel while avoiding any unwanted conversions? Thanks.

Using @Html.Raw results in this problem:

enter image description here

The first line is read correctly but with each line break it reads as code instead of text. I put the original @Html.Raw in quotes, is there a way to prevent it from attempting to read it as code as shown above?


Solution

  • It looks like you are struggling with HTML Encoding. Have you tried using @Html.Raw(Viewmodel.XML)? That helper should prevent MVC from HTML encoding the content.

    Depending on where that XML content comes from, you might be creating an XSS risk, so be careful how you use Html.Raw and consider reading more about it if it does solve this problem for you Is there a risk in using @Html.Raw?