Search code examples
c#asp.net-mvchtml-helperhttpcontext

Working of HTML/AJAX Helpers in .Net MVC


I think this might be pretty obvious for others but I cannot understand the working of these type of method overloads. The ones in which we only pass action method name.

How does these @Html.Helpers get the expected controller?

My guesses:

  1. That particular Helper extract it from the HttpContext
  2. this HtmlHelper htmlHelper parameter holds all the information related to the request.

I am trying to create a custom helper in which user should pass the name of the action method and it magically gets its respective controller.

When I checked the route-values in this HtmlHelper htmlHelper during run-time they showed me this-

  • {controller, Home}
  • {action, Index}
  • {id, null}

When I checked the HttpContext during run-time, it was null.

Expected output should be-

  • {controller, Device}
  • {action, Suggest}
  • {id, null}

If someone can provide behind the curtains working of default @Html.Helpers with examples that will be great.

UPDATE I did find what I was looking for. Here is the link to the question and its answer


Solution

  • All Html helpers have access to the HtmlHelper class. That reason is that these helpers are nothing else but extension methods of the HtmlHelper class.

     public static class HelperExtensions
     {
         public static string ControllerName(this HtmlHelper helper)
         {
                   string name = helper.ViewContext.Controller.GetType().Name
                   return String.Format("<span'>{0}</span>", name);
              }
         }
    }
    

    So everything regarding the current request is there.

    View.cshtml

    @Html.ControllerName()