1

In C#, I'm trying to convert a DataTable into a Javascript object through Razor syntax. However, when assigning string values to a Javascript key, the quote strings " get converted into HTML codes in Javascript \". How do I preserve the quote " in Javascript?

Example code:

<script type="text/javascript">
    @{
        string json = "";

        foreach (DataRow x in Model.MyDataTable.Rows)
        {
            json += "{field1: \"" + x["field1"].ToString() + "\"},";
        }

        json = json.TrimEnd(',');
    }

    var table = [@json];
</script>

What I'm expecting to see in Javascript debugger:

[{field1: "0001"}, {field1: "0002"}]

What I'm getting:

[{field1: \&quot;0001\&quot;}, {field1: \&quot;0002\&quot;}]

I've tried to use HttpUtility.JavaScriptStringEncode() but this was returning a similar issue.

1 Answer 1

3

You need to use RawString instead of default HtmlEncodedString

   var table = [@Raw(json)];
Sign up to request clarification or add additional context in comments.

2 Comments

Great, this works! Just FYI, as I'm using ASP.NET MVC, I needed to use Html.Raw() instead.
Have to wait 2 more mins before I can haha!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.