get the controller and action in MVC

Get The Controller And Action in MVC using HtmlHelper
To get controller and Action we will use the following code snippet. we can access it from routvalues collection
routeValues["controller"];
To get Action name we can use the following code snippet
routeValues["action"];
but for the ease of use we can use it in HtmlHelper. we embed these two statements to htmlhelper By using the power of Extension Methods in C#.
Add the following class to your MVC project


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

public static class HtmlRequestHelper
    {
       
        public static string Id(this HtmlHelper htmlHelper)
        {
            var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

            if (routeValues.ContainsKey("id"))
                return (string)routeValues["id"];
            else if (HttpContext.Current.Request.QueryString.AllKeys.Contains("id"))
                return HttpContext.Current.Request.QueryString["id"];

            return string.Empty;
        }

        public static string Controller(this HtmlHelper htmlHelper)
        {
            var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

            if (routeValues.ContainsKey("controller"))
                return (string)routeValues["controller"];

            return string.Empty;
        }

        public static string Action(this HtmlHelper htmlHelper)
        {
            var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

            if (routeValues.ContainsKey("action"))
                return (string)routeValues["action"];

            return string.Empty;
        }
}

Usage : you can use the above code in any view.cshtml Like the following with @Html


<div class="row">
   
    <div class="col-lg-12">
        <div class="col-lg-4">
            <label>Controller =</label>
            <label>@Html.Controller()</label>
        </div>
        <div class="col-lg-4">
            <label>Action =</label>
            <label>@Html.Action()</label>
        </div>
    </div>
</div>
The above code will return you the current controller and current requested action names

Post a Comment