Is it possible to get the view name from the layout?

I am trying to infer the name of the current view from my layout.

Usually used for this VirtualPath. Unfortunately, this will return the path to the layout file.

Is there a way to get the view name returned by the controller?

+4
source share
3 answers

Below you will get the name of the view:

((RazorView)ViewContext.View).ViewPath;
+6
source

You can use ViewBag . Define a property for it CurrentViewand use it.

public ActionResult Create()
{
  ViewBag.CurrentView = "Create";
  return View();
}

And in the layout you can read and use it as

<h2>@ViewBag.CurrentView</h2>

Or if you want to get it in a variable

@{ 
    var viewName = ViewBag.CurrentView;
}

If you do not want to explicitly specify the name of the viewbag property, you can write a special action filter for this.

public class TrackViewName : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        ViewResultBase view = filterContext.Result as ViewResultBase;
        if (view != null)
        {
            string viewName =view.ViewName;
            // If we did not explicitly specify the view name in View() method,
            // it will be same as the action name. So let get that.
            if(String.IsNullOrEmpty(viewName))
            {
                viewName =  filterContext.ActionDescriptor.ActionName;
            }
            view.ViewBag.CurrentView =  viewName;
        }
    }
}

[TrackViewName]
public ActionResult Create()
{     
  return View();
}
+3

If you are using MVC Core, you can use:

@System.IO.Path.GetFileNameWithoutExtension(ViewContext.View.Path)
0
source

Source: https://habr.com/ru/post/1619262/


All Articles