Friday, January 3, 2014

MVC get current Controller name and Action name

string controllerName = helper.ViewContext.Controller.ControllerContext.RouteData.Values["controller"].ToString();
            string actionName = helper.ViewContext.Controller.ControllerContext.RouteData.Values["action"].ToString();

////////////Tanks for interaction /////////////////////////
//some more explanatory code:

//sample to get names from action
 public ActionResult Index()
        {
            string currentControllerName = ControllerContext.RouteData.Values["controller"].ToString();
            string currentViewName = ControllerContext.RouteData.Values["action"].ToString();
            return View(db.Roles.ToList());//Roles- my class name
        }


//sample to get names from view
@model IEnumerable<DatabaseManager.Role>

@{
    ViewBag.Title = "Index";
    string currentControllerName =   ViewContext.Controller.ControllerContext.RouteData.Values["controller"].ToString();
    string currentViewName = ViewContext.Controller.ControllerContext.RouteData.Values["action"].ToString();
}

<h2>Index</h2>


2 comments: