I have a partial view (control) that\'s used across several view pages, and I need to pass the name of the current view back to the controller - so if there\'s e.g. validati
I had the same problem and that's how I solved it:
namespace System.Web.Mvc
{
public static class HtmlHelperExtensions
{
public static string CurrentViewName(this HtmlHelper html)
{
return System.IO.Path.GetFileNameWithoutExtension(
((RazorView)html.ViewContext.View).ViewPath
);
}
}
}
Then in the view:
var name = Html.CurrentViewName();
or simply
@Html.CurrentViewName()
Shouldn't you be using a validation method like Nerd Dinner implements?
That way you don't actually need to do all this and you can just return the View.
If you just want the action name then this would do the trick:
public static string ViewName(this HtmlHelper html)
{
return html.ViewContext.RouteData.GetRequiredString("action");
}
If you want to get the filename from within a partial view, this seems to work:
public static class HtmlHelperExtensions
{
public static string GetViewFileName(this HtmlHelper html, object view)
{
return @"\\"+ view.GetType().FullName.Replace("ASP._Page_", "").Replace("_cshtml", ".cshtml").Replace("_", @"\\");
}
}
And in the partial view, you should do something like this:
var filename = Html.GetViewFileName(this);
or this:
@Html.GetViewFileName(this)
Please do comment if this is not a good approach - any alternatives?