Why use Url.Content to reference resources?

In almost every ASP.NET MVC example I came across, I always see Url.Content , which is used to reference CSS, JavaScript, and images. No one has ever explained WHY to use it.

Anyone want to explain?

What is bad to do:

<img src="/Content/Img/MyImage.png" alt="My Image" />
<script src="/Scripts/jquery.js" type="text/javascript"></script>
<link href="/Content/Css/Default.css" rel="stylesheet" type="text/css" media="all" />
+5
source share
1 answer

You have the same work as Url.Content (). Url.Content () is similar to adding ~ to the beginning of your paths:

<script src="~/Scripts/jquery.js" type="text/javascript"></script>

It simply ensures that the path is always correct using routing. You can also use the Html helper method to make this easier:

public static string RenderScript(this HtmlHelper htmlHelper, string file) {
            var f = file.EndsWith(".js") ? file : string.Concat(file, ".js");
            return string.Format("<script src=\"/public/scripts/{0}\" type=\"text/javascript\"></script>", f);
        }

:

<%=Html.RenderScript("jquery")%>
+2

All Articles