Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Url.Content for referencing resources?

In almost every ASP.NET MVC example I've come across, I always see Url.Content being used to reference CSS, JavaScript, and Images. Not once has anyone explained WHY to use it.

Anyone care to explain?

What's so bad about doing:

<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" />
like image 697
Derek Hunziker Avatar asked Nov 06 '22 05:11

Derek Hunziker


1 Answers

What you have works the same as Url.Content(). Url.Content() is just like adding a ~ to be beginning of your paths:

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

Just ensures the path is always correct with routing. You can also make a 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);
        }

Then you can just put this in your masterpage:

<%=Html.RenderScript("jquery")%>
like image 200
Paul Avatar answered Nov 10 '22 19:11

Paul