I want to display the data from a ViewBag in my View with Javascript. Here is my code.
View
<span id='test'></span>
Javascript
function myFunction()
{
$('#test').text('@ViewBag.Test');
}
When myFunction()
is called I get the text @ViewBag.Test
but not his value. How can I fix this ?
You need to place your JavaScript which takes the
@ViewBag.Test
value in a page which is interpreted by the Razor view engine. My guess is that this is currently not the case.If you want to keep your javascript codebase separate from the view (which is entirely reasonable) you can use a global variable:
Alternatively, you can use a
data-*
attribute:What you should be ideally doing is passing the data to the view with a view model. Have a property to store that value you want to pass. For example. Let's think about a page to show the customer details and you want to get the last name in your javascript variable.
Your GET action method
and in your view which is strongly typed to your view model.
EDIT : (As per the question edit) To show the content on some event (ex : some button click), Store the value somewhere initially and then read it as needed and set it wherever you want.
Firstly make sure your
ViewBag.Test
does got a value, then use adiv
tag instead of aspan
and add the following code: