开发者

Why use Url.Content for referencing resources?

开发者 https://www.devze.com 2023-01-29 19:25 出处:网络
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.

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/jque开发者_如何学Gory.js" type="text/javascript"></script>
<link href="/Content/Css/Default.css" rel="stylesheet" type="text/css" media="all" />


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")%>
0

精彩评论

暂无评论...
验证码 换一张
取 消