How to prevent "being encoded as" in Razor?

3

Well the question here is that I'm working on a razor file and I'm wanting to create a json from an array in vb.net as follows:

For Each ItineraryPnr In ItinerariesNode.ChildNodes
    arrayPnrRetrieve(contPnr) = New With {Key .trasactionId = ItineraryPnr.SelectSingleNode("TransactionId").InnerText, .isSucces = False, .provider = ItineraryPnr.SelectSingleNode("Provider").InnerText, .pnr = ItineraryPnr.SelectSingleNode("PNR").InnerText, .errors = Nothing}
    contPnr = contPnr + 1
Next

Dim serializerPnrModel As New JavaScriptSerializer()
Dim jsonPnrRQ As String = serializerPnrModel.Serialize(arrayPnrRetrieve)

The above generates something like the following and I assign it to variable jsonPnrRQ :

[
  {
   "trasactionId":"c592360b-3d29-4689-9683-8b53b4880099",
   "isSucces":false,
   "provider":"4O",
   "pnr":"DBZD2N",
   "errors":null
  }
]

Then when wanting to assign it to a variable javascript in the following way:

 @<script>
     var metadata = {};            

     metadata.jsonEx = {};
     metadata.jsonEx.pnrRetrieve = @jsonPnrRQ;
     metadata.jsonEx.sequenceNumber = "3";

  </script>

It leaves me cycled the page and it sends me a syntax error, being that the variable jsonPnrRQ when debugging it is in a correct format.

The error is as follows:

Uncaught SyntaxError: Unexpected token &

The question would be if someone has happened to him and he has some solution for this?

  

When printing my object Js shows it to me in the following way

 metadata.jsonEx = {};
 metadata.jsonEx.pnrRetrieve = [{&quot;trasactionId&quot;:&quot;c592360b-3d29-4689-9683-8b53b4880099&quot;,&quot;isSucces&quot;:false,&quot;provider&quot;:&quot;4O&quot;,&quot;pnr&quot;:&quot;DBZD2N&quot;,&quot;errors&quot;:null}];
 metadata.jsonEx.sequenceNumber = "3";

And I think that may be the problem, so, the other question would be, does anyone have any idea why they assign it to me and how can I solve it? being that the variable jsonPnrRQ has its value well (this is because aldebugearlo comes out with the correct format).

    
asked by José Gregorio Calderón 14.03.2016 в 19:13
source

1 answer

3

Try the following:

metadata.jsonEx.pnrRetrieve = @Html.Raw(jsonPnrRQ);

The problem is that the content of the string jsonPnrRQ is being encoded as HTML and is converting the " in &quot; . This is how Razor works by default to avoid some security problems.

In this case we want to embed the content in the JavaScript code instead of displaying it as HTML text, with @Html.Raw() the content is sent as-is without coding it.

Also keep in mind that JSON is not the same as JavaScript. I recommend changing the JavaScriptSerializer for another library that serialize JSON like Json.NET

    
answered by 14.03.2016 / 19:34
source