Using Inline C# inside Javascript File in MVC Framework - javascript

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?

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.

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.

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.

.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"));
});

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.

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.

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

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

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

Related

How can I access embedded ASP.NET GlobalResources in JavaScript?

I'm working on a legacy ASP.NET project, which I'm trying to massage into shape slowly, but I can't make significant changes without it all collapsing like a chocolate finger house....
I've tried to find a solution for this, but failed miserably due to the specific mix of terminology ("javascript", "embedded" and/or "resource" just give me information as to how to embed a .js file...), and the fact that it's probably a weird way of doing things.
The project makes use of App_GlobalResources for translatable strings, which is used in C# code behind, the markup and in some of the JavaScript. For example:
HTML:
Text="<%$Resources: Resources, MeasuresLabel %>"
JS:
setDialogTitle('summaryDialog', physicalElementName, Resources.Resources.Summary);
This was all working fine, until we started using NUnit for some integration testing. To make the Resources.resx available to NUnit I've followed Scott Allen's suggestion, which works for NUnit but means that the above Resources.Resources is undefined.
So, my question is with this embedded file, how can I make it accessible to the JavaScript (or is there a better way I can make it available to NUnit)?
There's an the added complication due to the code I want to access it with being in separate .js files, rather than within script tags in the .aspx files.
EDIT
After looking at it some more, the real challenge is the properties that are accessed in the JS are static. Due to the number of places these are referenced, it's not practical to add a variable for each string that's being used.
I think that JS files aren't going through the ASP.NET engine and they are served as they are, that's why Resources.Resources.Summary isn't defined in your case, while it will work when embedded inside <script> tag in .aspx file.
The only way I know around this would be to store the used resource values in global javascript variables on the .aspx page and then use them in loaded JS files.

How can I separate an html page into parts without server script support?

I want to separate an html page into head, header, footer sort of stuff like that. And include them as I create a new page so that I won't have to update all pages if I change something in header or other parts of the included ones.
The problem is that I can do that easily with php support but the current server nginx(actually I don't really know what that means as a front-end dev) doesn't have that and won't do in the future. How can I accomplish that with pure html or with a little help of nginx?
You could use javascript includes.
For example if you were using jQuery…
page1.html
<div id="head"></div>
<script src="head.js"></script>
head.js
$('#head').html('<html goes here>');
If you don’t mind compiling before uploading you could use .kit files.
https://incident57.com/codekit/help.html#kit
And it’s not just for mac users…
Compile .kit files outside of Codekit

application-wide jquery script

I use some Facebook JS scripts for user authentification, etc. I want to place them in the properly unobtrusive way as application-wide scripts.
Currently I have the script as a partial and call it from my application header:
<%# render 'layouts/facebook_app_scripts' %>
The script works but is extremely obtrusive. I want to make it unobtrusive. This is especially important since I tap into all sorts of APIs and it's getting messy.
You don't need to see it in its entirety (if you need to see the script to answer this question, I don't think you'll be any help as this is a general question not script-specific)
You should know that it contains dynamically created links such as this one:
window.top.location = "<%= Facebook::SITE_URL.to_s %>/logout";
That means that putting this in a .js file in the assets/javascript folder isn't going to work, since .js files can't access rails-generated variables.
So how can I shift my javascript with dynamically-generated links from the rails view to an unobtrusive javascript file?
Take a look on this project to include all the Facebook JS SDK as a gem

Loading text file from web, and parsing it with a script?

My .html has some associated data in a .txt file that I need to load when the page is loaded. I then need a script to be able to parse that data and do stuff with it in the page. Is there a quick-n-dirty way to do this? I was thinking I could just have a hidden and then run through its innerHTML, but DIVs don't seem to support that.
Thanks in advance...new to web stuff!
EDIT: here's another catch: I want this to work, ideally, if the .html is loaded either from an actual website or from a local machine. To my knowledge, AJAX and XMLHttpRequest won't work in this situation(?)
Do you have flexibility in the format of the text file? If so I would store the data in the text file in JSON format and just include it in the HTML head of the page using script tags. Then you can use some JavaScript when the page is ready to parse the information stored in the text/JSON file and manipulate the HTML page as needed.
The nice thing about this approach is that it is simple and does not require server side code. You didn't mention whether or not the text file was dynamically generated but it doesn't matter with this approach.
You should use AJAX to load the text and a callback function to parse it according to your requirements and perform whatever actions are necessary. If you're using a framework like jQuery, look into the jQuery AJAX functions: http://docs.jquery.com/Ajax
If you're not using a framework and are instead coding straight JavaScript, look at using the XMLHttpRequest object: https://developer.mozilla.org/en/XmlHttpRequest
That should be done server side using a programming language like PHP or Perl or such. If you have to do it with JavaScript for some odd reason, the only way is to do AJAX call to the file and insert it into the DOM. There's plenty of tutorials for that.
And yes, innerHTML works on div elements, as well as with everything else.

Best practice on where to include javascript runtime dependent code in ASP.NET MVC apps

I have some javascript code that has in it localized messages that i pull from my resource files. My problem is that if i include my javascript files like...
<script scr="..." type="text/javascript"/>
in my masterpage for example, then the <%= Resources... %> code is not running on view rendering. My current way of resolving this problem is by including the full code inside script tags in my masterpage, but i don't like it.
Any better suggestions?
You need to close out all script tags as such for IE to accept the JavaScript:
<script>....</script>
Not
<script .... />
Understanding the problem
Inline asp.net tags (e.g. '<%= %>' are parsed at runtime when the server renders your page.
In order for ASP.Net to be able to parse documents it needs to be specified by the webserver that the extension is handled by the aspnet_isapi ISAPI extension.
The regular JavaScript files, to which you are adding asp.net code, will never run through this extension and thus will never be 'compiled' properly.
Now is there a solution?
Mads Kristensen has written a blogpost about this problem in 2008. It is still valid afaik and should do exactly what you need.
See http://madskristensen.net/post/Localize-text-in-JavaScript-files-in-ASPNET.aspx
He uses the .axd extension which is also handled by the aspnet_isapi ISAPI extension.
Another very good post which addresses the problem more specifically for asp.net mvc can be found here: http://afana.me/post/aspnet-mvc-internationalization.aspx
Hope this helps.

Categories

Resources