Is it possible to do the following from a javascript file in an MVC application?
$(function(){
alert(@ViewBag.someValue);
}
Currently it throws the error:
reference to undefined XML name @ViewBag
Is it possible to do the following from a javascript file in an MVC application?
$(function(){
alert(@ViewBag.someValue);
}
Currently it throws the error:
reference to undefined XML name @ViewBag
Create a view and return it as a partial view:
Then in the GlobalJS view add the javascript code like (adding the // will make visual studio intellisense read it as java-script)
Then in your final view you can add a reference to the javascript just like this.
Then in your final view controller you can create/pass your ViewBags and it will be rendered in your javascript.
Hope it helps.
Not in a JavaScript file, no.
Your JavaScript file could contains a class and you could instantiate a new instance of that class in the View, then you can pass
ViewBag
values in the class constructor.Or if it's not a class, your only other alternative, is to use
data
attributes in your HTML elements, assign them to properties in your View and retrieve them in the JS file.Assuming you had this input:
Then in your JS file you could get it by using: