sarsnake
sarsnake

Reputation: 27703

Images with razor asp.net mvc inside JS

I need to dynamically insert an image in my JS code. In my Razor template I have:

@section Includes {  
      <script type="text/javascript">   


        var imgPath = "@Url.Content("~/Content/img/")";
        alert(imgPath);

      </script>

}

Then in my JS I have:

 insertImg = "";
  if (response[i].someFlag == 'Y') {

                        insertImg = "<img src=\"" + imgPath + "/imgToInsert.gif\" width=\"6px\" height=\"10px\" />";
                    }

But it doesn't work - it will not find the image. The image is stored in /Content/img folder...

What am I doing wrong? I am guessing it is because it is mapping the image from Js script..looks like I will have to hardcode it?

Upvotes: 1

Views: 572

Answers (2)

Valamas
Valamas

Reputation: 24719

Alert or console.log the following to see if there are too many slashes " + imgPath + "/imgToInsert.gif"

Upvotes: 1

Erik Philips
Erik Philips

Reputation: 54618

It might be advantageous to use the MVC TagBuilder Class to build your image tags instead of using a string concatenations. Lets you build tags dynamically and makes sure they are well-formed. Most likely your tag is not well-formed.

Upvotes: 0

Related Questions