Search code examples
javascriptjsonasp.net-mvc-5viewdata

How to set a the value of a JavaScript Variable from my ViewData in ASP.NET MVC 5


I am doing some client side calculations in a JavaScript function. And for that I need a value from Server. I have set the value in ViewData["Period"] in ASP.NET MVC 5 controller and in my view I want to set this ViewData["Period"] in JavaScript variable so that when the page loads the value is loaded in that javascript variable from viewdata.

var corporateInfo;


function getRates(startDate,deliveryDate)
{
    //Do some calculation on client side based on corporateInfo,startDate, deliveryDate
}

function(areaCode)
{
// Do some calculation based on corporateInfo and areaCode
}

How to set the periodInfo in my asp.net mvc 5 view from ViewData when the page loads.?

Edited: Aug18 corporateInfo is class with several properties in it and one of the property returns array.


Solution

  • In my Asp.net MVC view I have added the below code. Because Corporate was a complex object that's what I had to serialize it first and then assign it to the JavaScript variable. For serializing C# complex object to json I have used JavaScriptSerializer class which is in System.Web.Script.Serialization namespace.

    @using System.Web.Script.Serialization
    
    <script type="text/javascript">
        @{
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string json = jss.Serialize(ViewData["Corporate"]);
            @Html.Raw(string.Format("corporateInfo = {0};", json));
        }
    </script>