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

僤鯓⒐⒋嵵緔 提交于 2019-12-05 10:52:43

The following will get you the view name:

((RazorView)ViewContext.View).ViewPath;

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

If you use MVC Core you can use:

@System.IO.Path.GetFileNameWithoutExtension(ViewContext.View.Path)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!