javascriptasp.net-mvcjsonasp.net-mvc-2

Dropping JSON object on html page in asp.net mvc2


I'm using asp.net mvc2 and I want to drop some JSON objects from my controller similar to validation metadata. When we call Html.ClientValidation() before our form it drops some JavaScript on the page like

<javascript type="text/javascript">
    <!--CDATA[validation metadata]-->
</javascript>

I want to have some JSON objects dropped in my page that I can use through jQuery


Solution

  • <script type="text/javascript">
        var obj = <%= new JavaScriptSerializer().Serialize(new { foo = "bar" }) %>;
    </script>
    

    Now you can use the obj global variable:

    alert(obj.foo);