简体   繁体   English

在ASP.NET MVC中获取控制器名称

[英]Get controller name in asp.net mvc

In my app I am creating a dynamic menu. 在我的应用程序中,我正在创建一个动态菜单。 The menu is populated depending upon the controller it is called for. 根据需要的控制器来填充菜单。 For example in one of my Controller name is Organization. 例如,我的控制器名称之一是组织。 To populate the menu for it I call this 为了填充菜单,我称之为

@Html.Action("Menu","Site", new { calledForController = "Organization", oId = @Model.Id })

Everything is working nice and smooth but the issue I am experiencing as I am having more views is that I have to put the above line in every view. 一切工作正常且流畅,但是当我拥有更多视图时,我遇到的问题是我必须在每个视图中都加上上述内容。 What I am looking for is a way to get the current controller and action name from the route data so that I don't have to call this on every view. 我正在寻找的是一种从路线数据中获取当前控制器和动作名称的方法,这样我就不必在每个视图上都调用它。

The ideal solution would be to write something like this 理想的解决方案是写这样的东西

@Html.Action("Menu","Site")

in my _Layout.cshtml and then in the menu controller populate menu list depending upon where it was called from. 在我的_Layout.cshtml中,然后在菜单控制器中填充菜单列表,具体取决于调用它的位置。

If I write 如果我写

this.ControllerContext.RouteData.Values["controller"].ToString();

in my Menu action of Site controller I am always getting Site as my controller name. 在“站点控制器”的“菜单”操作中,我总是将“站点”作为我的控制器名称。 Any thoughts on this? 有什么想法吗?

I have searched and found this as an appropriate solution for me, to get the Route data use this 我搜索并找到了适合我的解决方案,以使用此路线数据

var routeValues = HttpContext.Request.RequestContext.RouteData.Values;

if (routeValues.ContainsKey("id"))
   oId = (String)routeValues["id"];

This way in my _Layout.cshtml I can write this 这样在我的_Layout.cshtml中,我可以这样写

@Html.Action("Menu","Site")

And now I don't have to pass in extra called for controller again and again. 现在,我不必一次又一次地传递额外的要求控制器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM