1

I have a C#.Net MVC3 web app. In a certain js file I am loading a dialog box and assigning the loading: property the below image

loading: $('<img src="../../Content/Images/loading.gif" alt="loading" class="ui-loading-icon">'),

However, in different environments it does not find the image. The code in those instances should be

loading: $('<img src="../../../Content/Images/loading.gif" alt="loading" class="ui-loading-icon">'),

I tried

loading: $('<img src="@Href("~/Content/Images/loading.gif")" alt="loading" class="ui-loading-icon">'),

And also tried

loading: $('<img src="@Url.Content("~/Content/Images/loading.gif")" alt="loading" class="ui-loading-icon">'),

Neither worked....when I've used @Url.Content and @Href in the aspx files, it works.

Needless to say, I'm not a javaScript expert, but I figure this must be do-able in the js file.

Any ideas?

3
  • The @url.Content should work. Did you debug with firebug? Commented Jan 4, 2012 at 15:14
  • Can you show some more code? Its not clear what you are trying to do. Commented Jan 4, 2012 at 15:15
  • 2
    You can't use .NET code in the JS file as it is not processed by .NET. Commented Jan 4, 2012 at 15:16

2 Answers 2

4

The way I usually get around this is by creating a helper function in your master or layout page:

Place this in your layout page below the reference to jquery but above any other file that will use it:

// This adds the helper onto the jQuery object rather than just being global
$.getUrl = function (path) {
     return '@Url.Content("~")' + path;
};

Then use it like this in your js file:

$('<img src="' + $.getUrl('/Content/Images/loading.gif') + '" />')
Sign up to request clarification or add additional context in comments.

Comments

2

As Richard D stated you cannot run .NET code in a javascript file. A possible workaround is to stored the image path in a hidden field in your View and then get it from the javascript file.

View file:

<input type="hidden" id="image-path" value="@Url.Content("~/Content/Images/loading.gif")" />

JS file:

var imagePath = $("#image-path").val();
loading: $('<img src="' + imagePath + '" alt="loading" class="ui-loading-icon">'),

1 Comment

and RichardD...thanks. That's kind of what I thought. I'll try the above idea and let you know how it goes. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.