0

Is there a way to access ViewData from a separate JavaScript file like the way you can access it from embedded JavaScript code on your CSHTML?

I would like to separate my JavaScript code and have the data load directly in my JavaScript file instead of using a hidden field in my HTML and then access pull it by GetElementById as it seems tedious to pass the data from the HTML to JavaScript and then back to HTML again.

CSHTML file

@using StatisticOndoAppCore.Models.ViewModels;
@using { var info = (Shop)ViewData["ShopInfo"]; }

Embedded JavaScript code

subscriptionShopData = [
        { y: 'Uge ' + @info.currentWeek,         a: @info.creationsCurrentWeek },
        { y: 'Uge ' + @info.currentWeek - 1,     a: @info.creationsLastWeek },
        { y: 'Uge ' + @info.currentWeek - 2,     a: @info.creationsCurrentWeekMinusTwo },
        { y: 'Uge ' + @info.currentWeek - 3,     a: @info.creationsCurrentWeekMinusThree }
    ];

new Morris.Bar({
        element: 'bar-subscriptions-shop',
        data: subscriptionShopData,
...
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tjaydk
  • 281
  • 3
  • 8

1 Answers1

1

You can't access ViewData in JavaScript files, because JavaScript files are static files. But you can use a hidden input (or data attributes) and set value with ViewData. Then it enables you to access value of the hidden input in JavaScript.

See a similar Stack Overflow question: Access a Model property in a javascript file?

Update (the below code may be useful, but it is not tested)

@section scripts
{
    <script>
       $(function(){
        var  subscriptionShopData = [
        { y: 'Uge ' + @info.currentWeek,         a: @info.creationsCurrentWeek },
        { y: 'Uge ' + @info.currentWeek - 1,     a: @info.creationsLastWeek },
        { y: 'Uge ' + @info.currentWeek - 2,     a: @info.creationsCurrentWeekMinusTwo },
        { y: 'Uge ' + @info.currentWeek - 3,     a: @info.creationsCurrentWeekMinusThree }
       ];
    });
    </script>
    <script src="..."></script>// use subscriptionShopData  variable in this js
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
adem caglin
  • 22,700
  • 10
  • 58
  • 78