简体   繁体   中英

How to retrieve controller and action names from Html.Action that is rendered from different controller and action in ASP.NET MVC

I am having a problem in retrieving Controller and Action names in ASP.NET MVC. Below is my scenario.

Step 1:

I am rendering a Html.Action("sidebar","Helper") in my layout page. So Controller and Action for it would be like this.

Step 2:

I am trying to pass the current controller name and action name to the view of sidebar view. For example, if I am at HomeController, controller name would be 'Home' and not 'Helper' because HelperController is in the layout page and that is included in every page. I am trying to retrieve the names as in Step 3.

Step 3

public class HelperController:Controller{
    public PartialViewResult sidebar()
    {
       string con_action = ControllerContext.RouteData.Values["controller"].ToString()+"-"+ControllerContext.RouteData.Vaues["action"].ToString();
    }
}

My problem: It keep returning the controller name "Helper" and action name "sidebar" even if I navigate to Index action of HomeController. How can I fix that problem?

You can pass the current controller name and action name as parameters in the layout page like this

@Html.Action("sidebar", "Helper", new { thisController = ViewContext.RouteData.Values["controller"].ToString(), thisAction = ViewContext.RouteData.Values["action"].ToString() })

and then access them in the Helper controller

    public class HelperController:Controller{
            public PartialViewResult sidebar(string thisController, string thisAction)
            {
               string con_action = thisController + "-" + thisAction;
               ...
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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