Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Inline C# inside Javascript File in MVC Framework

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?

like image 932
Al Katawazi Avatar asked Jun 25 '09 18:06

Al Katawazi


Video Answer


2 Answers

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.

like image 125
Grant Wagner Avatar answered Sep 20 '22 03:09

Grant Wagner


.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"));
});
like image 44
Serhat Ozgel Avatar answered Sep 22 '22 03:09

Serhat Ozgel