简体   繁体   中英

.NET Core separating JavaScript from CSHTML and access ViewData

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,
...

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM