Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the View name from within Layout?

I'm trying to pull the name of the current View from within my Layout.

Usually, VirtualPath is used for this. Unfortunately, this will return the path of the Layout file.

Is there any way to get the name of the View that's returned by the controller?

like image 876
Jerad Rose Avatar asked Dec 09 '15 20:12

Jerad Rose


People also ask

Where is_ ViewStart cshtml called?

Running Code Before Each View Code that needs to run before each view or page should be placed in the _ViewStart. cshtml file. By convention, the _ViewStart. cshtml file is located in the Pages (or Views) folder.

What is_ ViewImports cshtml?

The purpose of the _ViewImports. cshtml file is to provide a mechanism to centralise directives that apply to Razor pages so that you don't have to add them to pages individually. The default Razor Pages template includes a _ViewImports. cshtml file in the Pages folder - the root folder for Razor pages.

What is layout View in MVC?

The layout view allows you to define a common site template, which can be inherited in multiple views to provide a consistent look and feel in multiple pages of an application. The layout view eliminates duplicate coding and enhances development speed and easy maintenance.


3 Answers

The following will get you the view name:

((RazorView)ViewContext.View).ViewPath;
like image 161
Harsh Shah Avatar answered Nov 07 '22 18:11

Harsh Shah


If you use MVC Core you can use:

@System.IO.Path.GetFileNameWithoutExtension(ViewContext.View.Path)
like image 40
Postlagerkarte Avatar answered Nov 07 '22 17:11

Postlagerkarte


You can use ViewBag. Define a CurrentView property to it and use that.

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

And in the layout, you can read and use it like

<h2>@ViewBag.CurrentView</h2>

Or if you want to get it into a variable

@{ 
    var viewName = ViewBag.CurrentView;
}

If you do not wish to explicitly set the viewbag property name, you can write a custom action filter to do that.

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's get that.
            if(String.IsNullOrEmpty(viewName))
            {
                viewName =  filterContext.ActionDescriptor.ActionName;
            }
            view.ViewBag.CurrentView =  viewName;
        }
    }
}

And you need to decorate your action methods with our new action filter

[TrackViewName]
public ActionResult Create()
{     
  return View();
}
like image 2
Shyju Avatar answered Nov 07 '22 17:11

Shyju