Is it possible to write the below line in js file
var lst = @Html.Raw(Json.Encode(ViewBag.List));
Is it possible to write the below line in js file
var lst = @Html.Raw(Json.Encode(ViewBag.List));
Html Helpers can be used only in Views and not in the JavaScript files. To make things work, you need to write your input variables to View and rest of the code in JavaScript files. So, your code should be like :
View:
<script>
var lst = @Html.Raw(Json.Encode(ViewBag.List));
</script>
and rest of the code to access "lst" will reside in javaScript file:
JS File:
$(document).ready(function(){
// access lst here, rest of the code goes here
});
Note: Do not forget to include JS file to View.
You cannot use server side code in static js files. You could declare this global variable in the view and then use from separate javascript files.
You can made you js file dynamic, such as any other asp.net file by renaming it in
filename.aspx
for example. Then your modded 'js' file will be something like:
<%@ Page Title="" Language="C#" %>
<%
Response.ContentType = "application/x-javascript";
%>
function foo() {
var a = "<%= myVar %>";
}
you can include in your page with the standard way:
<script type="text/javascript" src="filename.aspx"></script>
my fav solution is to give arguments as parameters:
function foo(parameter) {
var lst = parameter;
...
}
and in the View:
<input type='button' onclick="foo('@Html.Raw(Json.Encode(ViewBag.List))');" />
You may as well use an object to store every server side property and the pass it to your js as a global. Do it in the $(document).ready();
. There's already a good question on SO, with more insights ont this. Will edit later with the link.
Regards,
EDIT: give a read to this SO question you'll find some more insights.