Tuesday, October 3, 2023
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  51] [ 2]  / answers: 1 / hits: 27120  / 15 Years ago, thu, june 25, 2009, 12:00:00

I am trying to get inline C# to work in my JavaScript files using the MVC Framework. I made this little test code up.



$(document).ready(function() {
alert(<%= ViewData[Message] %>);
});


When this code is used inside of the view it works perfectly. When I get outside of my aspx view and try this in a JavaScript file I get illegal XML character. I figure this is by design in the MVC Framework but I haven't been able to find any material on this on the web.



Has anyone gotten inline C# to work in JavaScript files using the MVC Framework?


More From » asp.net-mvc

 Answers
9

As others have said, the C# is not being processed by the server.



A possible solution would be to have a separate view that uses the same model and outputs the JavaScript, then reference that view in your <script type=text/javascript src=yourJSview.aspx></script>.



Added as per SLaks' answer:



Set the content-type to text/javascript, and put your JavaScript source directly below the <%@ Page directive (without a <script> tag).



Beware that you won't get any IntelliSense for it in VS.


[#99242] Monday, June 22, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chauncey

Total Points: 377
Total Questions: 91
Total Answers: 99

Location: Jordan
Member since Thu, Aug 5, 2021
2 Years ago
;