Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Acessing ViewData Using Variable Name

$
0
0

I'm still new to .NET, and am struggling with something I'm hoping someone here can help me out with...

I've got a number of ViewData objects that I'm sending from my Controller to my View. What I want to be able to do is to dynamically access them in JavaScript. I was thinking about having something like this in my Razor View page:

<script type="text/javascript">
   function GetMyViewData(dataWanted) {
      var data = '@ViewData["' + dataWanted + '"]';
      return data
   }</script>

So I could call it from an external JS file like this:

var usefulInfo = GetMyViewData('DesiredDataNugget');
var moreStuff = GetMyViewData('AnotherBitOfData');
var otherStuff = GetMyViewData('OtherInfo');

But of course, that doesn't work. What am I missing? How can I use a variable in place of the name for the specific ViewData object?

Right now I have a bunch of hard-coded statements to get me by, but it seems like there should be a more dynamic way to do what I want...

Thanks!


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>