Archive for June, 2010

Safely locate & load resource in ASP.MVC view

June 9th, 2010 Comments off

In the context of ASP.MVC, a view can usually be used in different routes and hence loading resources(javascripts/images etc) using relative path may not work.

For example, a view index.aspx can be used in


And assume the resource is located in the root http://localhost/myweb/, IMHO there is no easy way to refer to the resources… trouble trouble…

That is why I have my little routine as an extension method of HtmlHelper

public static string ResolveResource(this HtmlHelper html,string url)
 return html.ViewContext.RequestContext.HttpContext.Request.ApplicationPath + "/" + url;

To use it, just do these in your view:

<script src="<%=Html.ResolveResource("/Content/media/js/jquery-1.3.2.min.js") %>"  type="text/javascript"></script>

Categories: ADO.Net, C#, Tech Tags: