Search code examples
javascriptjsonhtmlasp.net-mvc-4postmessage

javascript - how to send json by postmessage


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 &quot Why is that? and How can I post JSON string as it is?


Solution

  • 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