Well the question here is that I'm working on a razor file and I want to create a json from an array in vb.net
the following way:
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 the variable jsonPnrRQ
:
[
{
"trasactionId":"c592360b-3d29-4689-9683-8b53b4880099",
"isSucces":false,
"provider":"4O",
"pnr":"DBZD2N",
"errors":null
}
]
So 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 the page cycled and sends me a syntax error, since the variable jsonPnrRQ
when debugging it is in a correct format.
The error is the following:
Uncaught SyntaxError: Unexpected token &
The question would be if anyone has happened and has a solution for this?
When printing my object
Js
it shows it to me as follows
metadata.jsonEx = {};
metadata.jsonEx.pnrRetrieve = [{"trasactionId":"c592360b-3d29-4689-9683-8b53b4880099","isSucces":false,"provider":"4O","pnr":"DBZD2N","errors":null}];
metadata.jsonEx.sequenceNumber = "3";
And I think that may be the problem, so the other question would be, does anyone have an idea why it is assigned to me like this and how I can solve it? being that the variable jsonPnrRQ
has its value well (this is because when debugging it it comes out with the correct format).
Try the following:
The problem is that the content of the string
jsonPnrRQ
is being encoded as HTML and you are converting them"
to"
. This is how Razor works by default to avoid some security issues.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 being sent as is without encoding it.Also note that JSON is not the same as JavaScript. I recommend you change the
JavaScriptSerializer
for another library that serializes JSON like Json.NET