I upload a selected image to wwwroot
folder. That works.
I return the Razor page with a ViewData
containing the path. That doesn’t work.
This is what shows when I debug ViewData
in immediate debug window:
?ViewData["Uploaded"]
"~/images/DanceImages/bulltrout.jpg"
If I paste that path exactly into an img
tag, it works:
<img src="~/images/DanceImages/bulltrout.jpg" alt="" />
But if I try to reference the ViewData["Uploaded"]
on the Razor page, I just get the path displayed:
html:
@ViewData["Uploaded"].ToString()
displays this string:
~/images/DanceImages/bulltrout.jpg
So I tried using url.content syntax :
@Url.Content(ViewData["Uploaded"].ToString())
and I get the path displayed again but without the ~/
.
To summarize: the actual string cut from inside the ViewData
object when used with <img>
tag works.
Screenshot below has hardcoded path that works.
Then next is url.content
result
Then finally img
tag result
I can’t seem to reference the ViewData["Uploaded"]
on the Razor page.
1
Using Url.Content() is an effective way to generate the correct URL for static files stored in the wwwroot folder. Here’s my test:
<img src="/image/Untitled.png" />
<img src="~/image/Untitled.png" />
<h>@ViewData["imageUrl"]</h>
<img src=@ViewData["imageUrl"] />
<img src="@Url.Content("~/image/Untitled.png")" alt="Example Image" />
<img src="@Url.Content(ViewData["imageUrl"].ToString())" alt="Example Image" />
public IActionResult Index()
{
ViewData["imageUrl"] = "/image/Untitled.png";
return View();
}