Last post Sep 03, 2020 06:03 AM by Jerry Cai
Sep 02, 2020 01:41 PM|yogyogi|LINK
Why is "~" sign not taking the img tag to the root folder in asp.net core.
In my view i am setting the img's tag src attribute like this:
<img src="@Model.Logo" />
The Model.Logo has the value : ~/Images/user-management-identity.png The problem here is that "~" sign not resolving to root folder. I checked it on in the page source and found that the code of the img tag formed is.
<img src="~/Images/aspnet-core-model-validation.png" />
When I directly place the given img tag with it's src in the view then it works correctly. The below code works well.
<img src="/Images/user-management-identity.png" />
What is the reason??
Sep 02, 2020 02:16 PM|PatriceSc|LINK
Use <img src="@Url.Content(Model.Logo)" /> to force resolving your ~ prefix (or you could also resolve this when loading model data).
With earlier Razor versions you actually had also to do this for hardcoded values. As it is cumbersome they later added processing literal values for you.
As any design decision, doing that or not automatically when using variables could be discussed:
- they likely thought it is best to consider that you take then the responsability for providing the correct resolved value
- else it would be done for you without any way to opt-out and for example src="@value" and data-src="@value" would NOT render the same value
(also you can always opt for doing later but if you took the wrong decision it is too late as you already have code that relies on that)
Edit: another option could be to use your own image tag helper. For example maybe something such as :
<img asp-src="@Model.Logo" />
Sep 03, 2020 06:03 AM|Jerry Cai|LINK
The problem here is that "~" sign not resolving to root folder.
This does not work because '~' is not a feature of HTML or CSS.
From Asp.net MVC 4, we can write '~' with URLs in Html because Razor View Engine will parse the URLs.
And once we get into the src, it will not go back, so if we use @Model, src will not parse the ‘~’.
You can refer to the following link: