MVC3: What is the best way to get the view path fr

2019-04-24 18:45发布

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;
}

3条回答
放荡不羁爱自由
2楼-- · 2019-04-24 19:06

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.

查看更多
迷人小祖宗
3楼-- · 2019-04-24 19:10

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.

查看更多
你好瞎i
4楼-- · 2019-04-24 19:29

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

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

Good luck

查看更多
登录 后发表回答