13

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?

9 Answers 9

15

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.

1
5

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.

4
  • 1
    This is a great Idea, but in practice why would anyone want to do this, unless the result of the aspx view that contains the javascript could be cached. Because if not then this is the same as just embedding the script code directly into the main page where it is used. am i wrong?
    – 7wp
    Commented Apr 15, 2011 at 16:07
  • 1
    @Roberto: What if it's used by multiple pages?
    – SLaks
    Commented Apr 15, 2011 at 16:12
  • 1
    Well In that case yes. For re-use this is great way to solve it. But I was thinking more along the lines of replicating the cache-ability of traditionally included external JavaScript files.
    – 7wp
    Commented Apr 15, 2011 at 17:21
  • 1
    When I put JavaScript into external .js files instead of embedding it, I do it with the intent that it shrinks the size of my page to optimize load time, also allows the browser to cache this .js file for other pages that use it, so it does not have to re-download it every time. With the idea of putting JavaScript into a aspx file, it does provide re-usability & ability to insert inline c#, but loses the ability to cache it like a traditional externally linked .js file :( I wonder if there is a way around this.
    – 7wp
    Commented Apr 15, 2011 at 17:31
5

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.

4

.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"));
});
2
  • I think this is really the best solution I have seen. Another alternative would be to have a url I could go to that would spit out the message or link information I am looking for. Then I could use it at will. Commented Jun 25, 2009 at 18:33
  • 2
    @Serhat: Or <script>var msg = '<%= ViewData["Message"] %>';</script> in the view and $(document).ready(function() { alert(msg); }); in the JS file. One important point in both your solution and my suggestion, if "Message" might contain quotation marks or newline characters, special care must be taken to escape those otherwise you risk breaking the hidden input in your solution or the JavaScript variable assignment in my suggestion. Commented Jun 25, 2009 at 18:33
3

That inline C# has to be processed by the server in order to make sense. Naturally, it won't work with a just-plain-JavaScript file.

1
  • I figured as much but was hoping there might be something out there. I am trying to get my html helper class that gives me nice absolute links to work in the javascript files. Oh well Commented Jun 25, 2009 at 18:29
2

Your web server does not process .js files, it only serves them to the client. This is in contrast to .aspx or other ASP.NET file types. These files are interpreted by your server before they are served up to the client.

2

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

1

when you have C# code in a separate file and include it in your View the Server does not process the code, the script file will be called by the browser and the inline script would be treated as plain string

alternatively you can try script runat=server when including you script file but I am not sure about the effects of this

0

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".

Not the answer you're looking for? Browse other questions tagged or ask your own question.