I have a C# string variable having following serialized Json string:
{
"Video": "1",
"Voice": "1"
}
and I am trying to post it via postMessage
like this:
string jsonVerticalTypeQuantity = Newtonsoft.Json.JsonConvert.SerializeObject(VerticalTypeQuantity);
<script>
$(document).ready(function () {
parent.postMessage({ "SelectedComponent": "@jsonVerticalTypeQuantity"}, "*");
});
</script>
But when I check this in browser it adds extra characters like "
Why is that? and How can I post JSON string as it is?
The @
directive automatically encodes output string while used against a server-side Razor variable as encoded HTML. You should put @Html.Raw()
helper to return unencoded JSON string:
parent.postMessage({ "SelectedComponent": @Html.Raw(jsonVerticalTypeQuantity) }, "*");
Or use a variable as alternative:
@{
string jsonVerticalTypeQuantity = Newtonsoft.Json.JsonConvert.SerializeObject(VerticalTypeQuantity);
}
<script>
$(document).ready(function () {
var jsonData = @Html.Raw(jsonVerticalTypeQuantity);
parent.postMessage({ "SelectedComponent": jsonData }, "*");
});
</script>
Related issue:
MVC failed to make a json string in view for a variable in javascript