0

I am developing a mvc application.I wrote a jquery for different operations and saved in to a js file named my.js. And i included that js file into my page.

 <script src="../../Scripts/my.js" type="text/javascript"></script>      

How can i access ViewData from that js file. I tried many methods.But didnt worked yet. The code i used to access ViewData from js file is shown below.

 var CalanderPreference = "<%= ViewData["CalanderPreference"] %>";

But it returning an error like 'Expected ; '

Any ideas?

2 Answers 2

2

ViewData is not accessible on client, because it exists only on view rendering.

You could serialize your view data to json on server side, write it to hidden field, and them parse it to javascript object on client side.

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

Comments

2

You can create your javascript object on the view like in this example.

Put this into your view and not in a seperate file:

        <script type="text/javascript">
            $(function() {
                var saleYear = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Year %>");
                var saleMonth = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Month %>") - 1;
                var saleDay = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Day %>");
                var saleHour = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Hour %>");
                var saleMinute = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Minute %>");
                var saleSecond = parseInt("<%=ViewData.Model.Sale24Hours.EndDate.Second %>");
                var endSaleDate = new Date(saleYear, saleMonth, saleDay, saleHour, saleMinute, saleSecond);
                $("#countDownSale24").countdown({ until: endSaleDate, compact: true, format: "HMS" });
            });
        </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.