Using Url.Content with semi-relative URL

2019-02-12 01:42发布

I am storing the location of images in my database in an MVC application...but i am only storing part of the location. For example:

/headers/image1.jpg
/headers/image2.jpg

The images are actually stored in the following folder:

~/content/images/headers/image1.jpg
~/content/images/headers/image1.jpg

In my view, I want to do something like this:

<img src="@Url.Content("~/content/images") + Model.ImageUrl" />

How can I do this?

2条回答
放我归山
2楼-- · 2019-02-12 02:26

Just do it!

<img src="@Url.Content("~/content/images" + Model.ImageUrl)" />

UPDATE:

As of ASP.NET MVC 4 it is valid to use the tilde URLs directly in HTML as the Razor View Engine will parse the URLs. Like this:

<img src="~/content/images/@Model.ImageUrl" />
查看更多
Evening l夕情丶
3楼-- · 2019-02-12 02:32

You can write extension method which combine your ImageUrl with configured path to content directory.

<img src="@Model.ImageUrl.ToRelative()" alt="@Model.ImageAlt" />

PS
Remember about alt tag. ;)

查看更多
登录 后发表回答