MS_Tech_Programmer
MS_Tech_Programmer

Reputation: 53

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.

Upvotes: 0

Views: 3876

Answers (2)

MS_Tech_Programmer
MS_Tech_Programmer

Reputation: 53

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>

Upvotes: 0

Anders Abel
Anders Abel

Reputation: 69310

In your view, you can insert a small snippet of JavaScript that sets a global variable:

<script>
Period = @ViewData["Period"]
</script>

That will render to a script that sets the global Period variable with the current value from ViewData, then you can access that variable from your calculation script.

Since the variable is global, you might want to give it a longer name to guarantee that it will be unique.

Upvotes: 1

Related Questions