0

in js variable i am trying to store image url using razon syntax but getting error. here is my sample code.

$(document).ready(function () {
   var loader = '@Url.Content("~/images/loader.gif")';
});

i follow this post https://stackoverflow.com/a/21486213/728750 https://stackoverflow.com/a/29798960/728750

but i follow the same syntax but in my case i am getting error. my js code is in separate file....not in view file.

looking for suggestion. thanks

EDIT

i have this code in my main view at top.

<script>
    var loaderUrl
    $(document).ready(function () {
        var loaderUrl = '@Url.Content("~/images/loader.gif")';
        alert(loaderUrl);
    });
</script>

later i try to access this variable loaderUrl in external js file which is loading at bottom of my main view......but still no luck.

1
  • What is the resulting client-side output? What is the error? Commented Dec 29, 2015 at 18:35

3 Answers 3

4

You can't. Store url in hidden field value in cshtml:

<input type='hidden' value='@Url.Content("~/images/loader.gif")' id='loaderUrl' />

And in js:

$(document).ready(function () {
   var loader = $('#loaderUrl').val();
});
Sign up to request clarification or add additional context in comments.

Comments

2

You cannot use @Url.Content("~/images/loader.gif") in a separate JS file. This has to be added to the view. What can you do is to create a global JS variable set it in your view and use it in your external JS.

Add this to your view. Then use the loaderUrl in your external JS file.

<script>
   var loaderUrl= '@Url.Content("~/images/loader.gif")';
</script>

3 Comments

loaderUrl is getting undefined in externel js file....i checked there by alert() function.
Make sure it's loaded before your external JS. Remove document.ready and give it a try
what do u mean by sucks?
1

When you have javascript in separate file then Razor syntax won't work in JS file. What I did when I had this issue it to keep variable in _commonJsGobal.cshtml and declared the variables required to access from JS files.

on _commonJsGlobal.cshtml add below script:

<script>
    var ROOT = '@Url.Content("~/")';
</script>

Then in your JS file use it like:

$(document).ready(function () {
   var loader = ROOT + '/images/loader.gif")';
});

Make sure the this partial gets rendered on required views on top of everything.

2 Comments

see my edit section. there i said what approach i am following.
You declared the loaderVariable two times. Only declare it once and out of scope of functions.

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.