html - .NET Core separating JavaScript from CSHTML and access ViewData -


is there way access viewdata separate javascript file way can access embedded javascript code on cshtml?

i separate javascript code , have data load directly in javascript file instead of using hidden field in html , access pull getelementbyid seems tedious pass data html javascript , 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 static files. can use hidden input (or data attributes) , set value viewdata. enables access value of hidden input in javascript.

see similar stack overflow question: access model property in javascript file?

update (the below code may useful, 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 js } 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -