Home > ADO.Net, C#, Tech > Safely locate & load resource in ASP.MVC view

Safely locate & load resource in ASP.MVC view

June 9th, 2010

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

http://localhost/myweb/r1

http://localhost/myweb/

http://localhost/myweb/r1/subr1

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>

Share
Categories: ADO.Net, C#, Tech Tags:
Comments are closed.