Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MVC3, how to get the current action name?

Is there a way to use HttpContext or the View context to get the current action name?

I can get the controller name using

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

    if (routeValues != null) 
    {
        if (routeValues.ContainsKey("controller"))
        {
            controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
        }
    }
}
like image 691
Chris Ballance Avatar asked Dec 17 '13 05:12

Chris Ballance


People also ask

How do I find my current controller name?

Get controller name In preceding code, we use the ViewContext object to access the RouteData of the current request. After that, we use the Values property to access the current routing path values. By passing the controller key to the Values property we can get the current controller name.

How do you get the names of the current action and controller in the view?

From your view you can simply use the extension methods off the Html object: @Html. Controller(); @Html. Action(); @Html.Id(); @Html.

Can you change the action method name?

You can have the same name, but make sure that the method signature is different. To do that, you can simply add a parameter to your post method.

How can use same action name in MVC?

While ASP.NET MVC will allow you to have two actions with the same name, . NET won't allow you to have two methods with the same signature - i.e. the same name and parameters. You will need to name the methods differently use the ActionName attribute to tell ASP.NET MVC that they're actually the same action.


1 Answers

var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;
if (routeValues != null) 
{
    if (routeValues.ContainsKey("action"))
    {
        var actionName = routeValues["action"].ToString();
    }
}
like image 78
Chris Ballance Avatar answered Oct 20 '22 18:10

Chris Ballance