7

I have an html extension method to retrieve the URL for a file that is located in the same folder as the view.

Example

/Views/Home/Index.cshtml
/Views/Home/Index.js
/Views/Home/Index.css

Is this the best way to do this? I don't like it because I have to do the following cast. I am sure that RazorView is not going to work if you are using a different view engine, but IView only has a Render method on it.

((RazorView)helper.ViewContext.View).ViewPath

Here is the full method

public static string GetUrl(this System.Web.Mvc.HtmlHelper helper, string fileName) {
    string virtualPath = ((RazorView) helper.ViewContext.View).ViewPath;
    virtualPath = virtualPath.Substring(0, virtualPath.LastIndexOf("/") + 1);
    return virtualPath + fileName;
}
Leslie Hanks
  • 2,347
  • 3
  • 31
  • 42
  • What are you eventually going to do with the URL? Insert it into some HTML and send it to the browser? If yes, this is unlikely to work since the Views subdirectory is protected and not accessible via a URL. – Codo Aug 14 '11 at 17:15
  • I have already made these files accessible via web.config by removing BlockViewHandler from the list of handlers. – Leslie Hanks Aug 14 '11 at 17:18
  • Are you sure this is a good thing to do? Don't you mind if people download your .cshtml files to inspect them for security bugs? – Codo Aug 14 '11 at 17:20
  • I'm not entirely sure if this is a good thing. I have verified that the cshtml files cannot be downloaded. I prefer to organize my code this way, but was not sure how to make it easy to code and maintain that way. Any recommendations are welcome. – Leslie Hanks Aug 14 '11 at 17:22

3 Answers3

6

If you use Razor view engine, You can use this:

((System.Web.Mvc.RazorView)htmlHelper.ViewContext.View).ViewPath

Good luck

Amit
  • 15,217
  • 8
  • 46
  • 68
1

I'm using something like this:

public static string GetUrl(this HtmlHelper html, string filename)
{
    var viewPath = ((WebViewPage)html.ViewDataContainer).VirtualPath;
    var viewFolder = viewPath.Substring(0, viewPath.LastIndexOf("/") + 1);
    var virtualScriptPath = viewFolder + filename;

    var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
    return urlHelper.Content(virtualScriptPath);
}

There is a cast to WebViewPage there, but I think (correct me if I'm wrong) that it will work regardless of whether you are using Razor or Webforms view engine.

gschuager
  • 1,919
  • 1
  • 16
  • 25
-3

You can get the current URL using this: How to get current page URL in MVC 3. And then parse the URL from there.

HTH.

Community
  • 1
  • 1
Brian Mains
  • 50,520
  • 35
  • 148
  • 257