mohsinali1317
mohsinali1317

Reputation: 4425

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.

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?

Upvotes: 1

Views: 1453

Answers (1)

mohsinali1317
mohsinali1317

Reputation: 4425

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

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

And now I don't have to pass in extra called for controller again and again.

Upvotes: 1

Related Questions