0

Is it possible to write the below line in js file

var lst = @Html.Raw(Json.Encode(ViewBag.List));
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
user930453
  • 71
  • 1
  • 1
  • 13

4 Answers4

1

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.

VikrantMore
  • 903
  • 7
  • 25
1

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • It was a global variable its working properly. In the same page i am using custom check box. Because of this `@Html.Raw` check box was not working – user930453 Nov 08 '11 at 07:14
  • @user930453, I can't see any relation between the `lst` js variable and some checkbox. Unless of course your custom checkbox relies on it. – Darin Dimitrov Nov 08 '11 at 07:16
  • By using custom checkbox, i am changing the image of the checkbox. If i remove this line, the image is appearing properly – user930453 Nov 08 '11 at 07:52
  • @user930453, so maybe you would like to show us your code so that we can tell you what is wrong with it? – Darin Dimitrov Nov 08 '11 at 08:05
1

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>
ʞᴉɯ
  • 5,376
  • 7
  • 52
  • 89
0

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.

Community
  • 1
  • 1
BigMike
  • 6,683
  • 1
  • 23
  • 24