I'm using ASP.NET Core 2 with Razor to try and pass an image URL into the View via a ViewModel. Unfortunately, the image URL has spaces in it, which I don't have control over at the moment.
I have a file name like this (note the space):
https://example.com/images/file name.jpg
I'm using Razor to try and show the image like this:
<img src=@item.ImageUrl />
The output HTML looks like this:
<img src="https://example.com/images/file" name.jpg />
Obviously this will not do! I should mention, we know this all works when we use an image that has no spaces in the file name. Here are some ways I've tried to correct the issue:
Using Url.Content
helper in Razor (this did not make a difference):
<img src=@Url.Content(item.ImageUrl) />
Using System.Web.HttpUtility.UrlEncode
when populating the ViewModel (this results in a "double-encoding" error):
myViewModel.ImageUrl = HttpUtility.UrlEncode(someUrl);
My goal is to get the URL encoded properly (no "double-encoding" and no truncating at the space in the input string). How can I achieve this goal?
The problem is that Razor will attempt to create valid HTML, so when it sees a space it automatically closes the quotation marks, so:
@{string img = "a a.jpg";}
<img src=@img />
Gets rendered as
<img src="a "a.jpg /> // of course invalid
So, you need to be sure you include your quotation marks, then Razor will use them:
<img src="@img" />
Which gets rendered as
<img src="a a.jpg" />
You can try
<img src="@Html.Raw(item.ImageUrl)" />
but I agree that using invalid URLs (with spaces) doesn't seem very useful in the long run.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.