0

I would like to access ViewBag data from within client side code. This is what I've tried in my controller:

ViewBag.Tasks = new JavaScriptSerializer().Serialize(tasks);

In my view I would then put this in a hidden field so that it available client side:

<input type="hidden" name="diagramData" data-nodes="@ViewBag.Tasks"  />

In my Javascript file, I would then search for the info related to the selected node:

alert($("#diagramData").data("nodes"));  //?????

The alert always shows "undefined". Why is this?

Amanda
  • 159
  • 1
  • 3
  • 16

1 Answers1

1

That's the wrong jQuery selector to retrieve the element. Try:

$('input[name="diagramData"]').data("nodes")

You set the name attribute in the HTML, yet you try to select it by id (because of the #). The attribute-equals selector is required to select by name.

Or, of course, just add an id parameter as "diagramData" and use your original selector.

Reference:

Ian
  • 50,146
  • 13
  • 101
  • 111