I'm dealing with a web application that resides within a subdirectory on a domain, and I'm attempting to discern the most idiomatic way of inserting a proper URL into an img
tag. While the following both produce the same HTML on the client machine, I'm not sure which is more "correct"
我正在处理一个驻留在域上的子目录中的Web应用程序,我试图辨别将最合适的URL插入到img标记中的最惯用的方法。虽然以下两者在客户端计算机上生成相同的HTML,但我不确定哪个更“正确”
<img src="~/Content/images/blah.png" />
<img src="@Url.Content("~/Content/images/blah.png")
Both of these produce an absolute path of /subfolder/Content/images/blah.png
, so both work, but I'm curious which one is the right way of doing it.
这两个都产生/subfolder/Content/images/blah.png的绝对路径,所以两者都有效,但我很好奇哪一个是正确的方法。
Is there any difference between these two approaches (for example, is one being resolved by a different mechanism than the other?), or is the former just syntactic sugar for the latter?
这两种方法之间是否存在差异(例如,一种方法是通过与另一种方法不同的机制解决的?),还是前者只是后者的语法糖?
3 个解决方案
#1
14
With MVC4 you no longer need @Url.Content
使用MVC4,您不再需要@ Url.Content
If Razor detects ~/ it would created an output identical to @Url.Content.
如果Razor检测到〜/它会创建一个与@ Url.Content相同的输出。
http://www.beletsky.net/2012/04/new-in-aspnet-mvc4-razor-changes.html
#2
4
Nothing is "more correct". I would use the shorthand since Razor now supports it.
没有什么是“更正确”。我会用速记,因为Razor现在支持它。
#3
0
if you are passing string through controller, you need to use @url.content(). but it you are passing path directly in .cshtml, no need to use @url.content().
如果要通过控制器传递字符串,则需要使用@ url.content()。但是你直接在.cshtml中传递路径,不需要使用@ url.content()。
Ex. No need.
防爆。没必要。
<img src="@Url.Content("~/Content/images/blah.png") />
NEED
@ViewBag.ImagePath = "~/Content/images/blah.png";
<img src="@Url.Content(@ViewBag.ImagePath)" />
#1
14
With MVC4 you no longer need @Url.Content
使用MVC4,您不再需要@ Url.Content
If Razor detects ~/ it would created an output identical to @Url.Content.
如果Razor检测到〜/它会创建一个与@ Url.Content相同的输出。
http://www.beletsky.net/2012/04/new-in-aspnet-mvc4-razor-changes.html
#2
4
Nothing is "more correct". I would use the shorthand since Razor now supports it.
没有什么是“更正确”。我会用速记,因为Razor现在支持它。
#3
0
if you are passing string through controller, you need to use @url.content(). but it you are passing path directly in .cshtml, no need to use @url.content().
如果要通过控制器传递字符串,则需要使用@ url.content()。但是你直接在.cshtml中传递路径,不需要使用@ url.content()。
Ex. No need.
防爆。没必要。
<img src="@Url.Content("~/Content/images/blah.png") />
NEED
@ViewBag.ImagePath = "~/Content/images/blah.png";
<img src="@Url.Content(@ViewBag.ImagePath)" />