Hướng dẫn html raw javascript

Is it possible to write the below line in js file

var lst = @Html.Raw(Json.Encode(ViewBag.List));

asked Nov 8, 2011 at 6:52

2

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.

answered Nov 8, 2011 at 7:03

Darin DimitrovDarin Dimitrov

1.0m266 gold badges3249 silver badges2911 bronze badges

4

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:


answered Nov 8, 2011 at 8:00

ʞᴉɯʞᴉɯ

5,1247 gold badges49 silver badges84 bronze badges

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:


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.

answered May 3, 2019 at 6:28

Hướng dẫn html raw javascript

VikrantMoreVikrantMore

8137 silver badges24 bronze badges

my fav solution is to give arguments as parameters:

function foo(parameter) {
   var lst = parameter; 
   ...
}

and in the View:


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.

answered Nov 8, 2011 at 8:06

BigMikeBigMike

6,5131 gold badge25 silver badges24 bronze badges

Not the answer you're looking for? Browse other questions tagged javascript asp.net-mvc or ask your own question.