2

I create a helper and i want to get view's path in this helper code, How can i do that?

I try code below. It will use view that return from action. So If i use this helper in partial view it will get parent view name instead.

RazorView view = helper.ViewContext.View as RazorView;      
viewPath = view.ViewPath;

Thank you in advance.

5
  • Why would you need that?? Commented Sep 2, 2014 at 8:14
  • try this ((System.Web.Mvc.RazorView)htmlHelper.ViewContext.View).ViewPath Commented Sep 2, 2014 at 8:20
  • @Shiv it's same thing as my code. if it's in partial view it will return parent view name not the partial one. Commented Sep 2, 2014 at 8:22
  • 2
    AFAIK, you can get the path with string path = helper.ViewDataContainer as WebPageBase).VirtualPath; but its not very elegant and you would have to parse the value Commented Sep 2, 2014 at 8:30
  • @StephenMuecke Add it as an answer. :) Commented Sep 2, 2014 at 9:41

1 Answer 1

4

You can retrieve the path of the view or partial view using

string path = (helper.ViewDataContainer as WebPageBase).VirtualPath;

This will return something like ~/Views/Home/MyPartial.cshtml

Sign up to request clarification or add additional context in comments.

1 Comment

What is 'helper' ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.