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() {
ale
This is an old question, but for those who stumble upon in through google in the future, the best solution is to use data-* attributes to pass in the variables. A hidden element could be used, but you might as well use the <script>
tag itself, and give it a unique ID.
A full example is answered here: https://stackoverflow.com/a/18993844/1445356
I agree with Serhat. It's best to render an HTML Hidden field, or, as Al mentioned, go to a URL for it. This can be done through a Web Service or even an IHttpHandler implementation. Then you could use a url such as "messages.axd?id=17".
You could make an ASPX view that renders JavaScript.
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.
.aspx files are the view files of MVC framework. The framework only renders the views and partial views. I do not think there would exist a way to use server-side code inside javascript files.
You can include your message in a hidden field
<%-- This goes into a view in an .aspx --%>
<%= Html.Hidden("MyMessage", ViewData["Message"]) %>
and use that inside your javascript file:
// This is the js file
$(document).ready(function() {
alert($("#MyMessage").attr("value"));
});
To add to Grant Wagner's answer and SLaks's answer, you can actually fool Visual Studio into giving you IntelliSense in his solution like so:
<%if (false) {%><script type="text/javascript"><%} %>
// your javascript here
<%if (false) {%></script><%} %>
In his solution it is required that when it renders to the page that there be no <script>
tags, but that has a side effect that turns off JavaScript IntelliSense in Visual Studio. With the above, Visual Studio will give you IntelliSense, and at the same time not render the <script>
tags when executed.
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.