MVC3: What is the best way to get the view path from an HtmlHelper object?

I have an html extension method to retrieve the url for a file that is 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 next cast. I am sure that RazorView will not work if you use a different viewing mechanism, but IView only has a Render method.

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

Here is the complete 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; } 
+7
source share
3 answers

If you are using the Razor view engine , you can use this:

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

Good luck.

+6
source

I am 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 broadcast in WebViewPage, but I think (correct me if I am mistaken) that it will work regardless of whether you use the Razor or Webforms viewing engine.

+1
source

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

NTN.

-3
source

All Articles