0

Is it possible to write the below line in js file

var lst = @Html.Raw(Json.Encode(ViewBag.List));
2
  • you mean put a @ before the variable name? Commented Nov 8, 2011 at 6:54
  • @James.Xu that is razor. Commented Nov 8, 2011 at 6:55

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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, I can't see any relation between the lst js variable and some checkbox. Unless of course your custom checkbox relies on it.
By using custom checkbox, i am changing the image of the checkbox. If i remove this line, the image is appearing properly
@user930453, so maybe you would like to show us your code so that we can tell you what is wrong with it?
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>

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.