[英]Is there a difference between Url.Content(“~/…”) and “~/” for urls in ASP.NET MVC?
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. 我正在处理一个位于域的子目录中的Web应用程序,我试图辨别出将正确的URL插入
img
标记的最惯用的方法。 While the following both produce the same HTML on the client machine, I'm not sure which is more "correct" 虽然以下两者在客户端计算机上生成相同的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? 这两种方法之间是否存在差异(例如,一种方法是通过与另一种方法不同的机制解决的?),还是前者只是后者的语法糖?
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 http://www.beletsky.net/2012/04/new-in-aspnet-mvc4-razor-changes.html
Nothing is "more correct". 没有什么是“更正确”。 I would use the shorthand since Razor now supports it.
我会用速记,因为Razor现在支持它。
if you are passing string through controller, you need to use @url.content(). 如果要通过控制器传递字符串,则需要使用@ url.content()。 but it you are passing path directly in .cshtml, no need to use @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)" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.