asp.net-mvc 使用带有半相对 URL 的 Url.Content
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5331777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Url.Content with semi-relative URL
提问by Dismissile
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:
我将图像的位置存储在我的数据库中的 MVC 应用程序中……但我只存储了该位置的一部分。例如:
/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?
我怎样才能做到这一点?
回答by Mikael ?stberg
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:
从 ASP.NET MVC 4 开始,直接在 HTML 中使用波浪号 URL 是有效的,因为 Razor 视图引擎将解析 URL。像这样:
<img src="~/content/images/@Model.ImageUrl" />
回答by dariol
You can write extension method which combine your ImageUrl with configured path to content directory.
您可以编写扩展方法,将您的 ImageUrl 与内容目录的配置路径相结合。
<img src="@Model.ImageUrl.ToRelative()" alt="@Model.ImageAlt" />
PS
Remember about alt tag. ;)
PS
请记住alt标签。;)