Vladimir  Mootin
Vladimir Mootin

Reputation: 128

How to change img src in view MVC

This is my image:

<img id="1star" src="~/Content/Images/emptystar.png" onmouseover="setStars(1)" onmouseout="setStarsBack()" onclick="location.href='@Url.Action("SetRating", "CreativeModels", new { id = GlobalVariables.CurrentBookId, rating = 1 })'" />

this is the code of function that should change the image source:

function setStars(amount) {
   if (amount > 0) {
     document.getElementById("1star").src = "~/Content/Images/filledstar.png";
   }
}

It changes but browser says, that it can't load the image. This is what browser shows after moving mouse to the pictures:

image of what browser shows

And this is picture of how images looked before moving mouse to them:

image with starts rendered

How should I change src property?

Upvotes: 3

Views: 3785

Answers (2)

user1567453
user1567453

Reputation: 2095

The problem is not with the src attribute. That is changed correctly to what you've set it to. The problem is that it's pointing to the wrong directory.

Assuming that you're using razor with your MVC solution try this out:

function setStars(amount) {
   if (amount > 0) {
     document.getElementById("1star").src = "@Url.Content("~/Content/Images/filledstar.png")";
   }
}

Upvotes: 1

Danibix
Danibix

Reputation: 235

You can try to base your image URL on the current html file position. Actually, using ~ in your image URL, you are assuming that it is located under the current user home folder. But if the user change, than ~ will point to the new user home folder.

I suggest to you to change the current the value of the src tag to this:

<pathOfHtmlFile>/Content/Images/filledstar.png

and replace <pathOfHtmlFile> with the path where the html file is located on your computer.

Upvotes: 0

Related Questions