Working on an ASP. net mvc application and needed the abilityResolve a URLFromPartial View. For example, I have an image I want to display, but I need to resolve the virtual path (say ,~ /Content/images/new.png) into a relative path that the browser can use, such as..././content/images/new.png or/Myappname/Content/images/new.png.
A standard view derives from the system. Web. UI. Page class, meaning you have access to the resolveurl and resolveclienturl methods. Consequently, you can write markup/code like the following:
'/>
The problem is that the above Code does not work as expected inPartial View. What's a little confusing is that while the above Code compiles and the page, when visited through a browser, renders, the call to page. resolveclienturl returns precisely what you pass in ,~ /Content/images/new.png, in this instance. The browser doesn't know what to do ~, It presumes it's part of the URL, so it sends the request to the server for the image with ~ In the URL, which results in a broken image.
I did a bit of searching online and found this handy tip from Stephen Walther-using resolveurl in an HTML helper. in a nutshell, Stephen shows how to create an extension method for the htmlhelper class that uses the urlhelper class to resolve a URL. specifically, Stephen shows how to add an image Extension Method to htmlhelper. I ininitialized Stephen's code into my codebase and also created a more generic extension method, which I named resolveurl.
View Source
Print?
1 |
public static MvcHtmlString ResolveUrl(this HtmlHelper htmlHelper, string url) |
3 |
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext); |
4 |
return MvcHtmlString.Create(urlHelper.Content(url)); |
With this method in place you can resolve a URL in a partial view like so:
'/>
Or you cocould use Stephen's HTML. image Extension Method (although my more generic HTML. resolveurl method cocould be used in non-image related scenarios where you needed to get a relative URL from a virtual one in a partial view ). thanks for the helpful tip, Stephen!
Determining whether a string is contained within a String Array (Case Insensitive)
if (stringArrayName.Contains("valueToLookFor", StringComparer.OrdinalIgnoreCase)) |