javascriptasp.nettelerik

How to transfer a serialized JSON string from C# code behind to use in Javascript


The ultimate goal here is to populate fields of a Bootstrap modal from an object in the C# code behind that has all the data I need. I serialized the object from the code behind, like this:

JavaScriptSerializer serializer = new JavaScriptSerializer();
sJSON = serializer.Serialize(aerationsystem.AerationSystem);

Now I want to reference that JSON in my Javascript function, like this:

</form>
    <script type="text/javascript">
        function fillModal() {
            var diameterValue = document.getElementById('diameter');            
            var aeration = <%# sJSON %>;
            diameterValue.innerText = aeration.dBinDiameter;
        }
    </script>
</asp:Content>

(I included that closing form tag and the closing asp:Content tag so you all could see where it was that I put this Javascript: at the very end of the file.)

However, when I call that Javascript function, this is what I see in the browser's debugger:

    <script type="text/javascript">
        function fillModal() {
            var diameterValue = document.getElementById('diameter');            
            var aeration = ;
            diameterValue.innerText = aeration.dBinDiameter;
        }
    </script>

I got the idea from here: Any way to pass an object from c# code behind to javascript? But, the means of accessing that JSON variable does not work for me. I've tried moving my script, but when I do that, I get an error that says "The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).". And I've tried other delimiters, like <%= %>, but I get the same errors depending on script placement. What am I doing wrong? How can I get that JSON string to show up in my Javascript function?


Solution

  • Instead of using a Literal control, I ended up using a <asp:HiddenField> control on the page to store the value. Then, I pulled that its value into the JavaScript variable.

    The hidden field: <asp:HiddenField ID="JsonLiteral" runat="server" />

    The code in the event that assigned the value:

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    JsonLiteral.Value = serializer.Serialize(aerationsystem.AerationSystem);
    

    And the JavaScript that finished the job:

    function fillModal() 
        {
            $(document).ready(function () {
                var diameter = document.getElementById('diameter');
                var control = document.getElementById('<%= JsonLiteral.ClientID%>');
                var aeration = JSON.parse(control.value);
    
                diameter.innerText = aeration.dBinDiameter;
            });
        }
    

    (There's a lot more to it than just that one property, of course.)