0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.