Identify the Area, Controller, and Action of a View

3

I need to create an HtmlHelper (MVC 4, C #) that identifies and reports the Area, Controller, and Action of a View. I'm not getting anything.

How can this be done? Is there a function or method that already does this?

    
asked by anonymous 06.10.2014 / 16:37

1 answer

3

In a basic MVC project you can do the following:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var e = this.RouteData.Values;

        string controllerName = (string)e["controller"];
        string actionName = (string)e["action"];

        return View();
    }
}

If you want to get these values in generic mode (especially in filters), you can access RouteData through the OnActionExecuting method (there are others that come from this too):

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var routeData = filterContext.RouteData; // aqui também

        base.OnActionExecuting(filterContext);
    }

Add-in : Collecting Data Through an Extension

Create a class within the ~ / Extensions / folder named LocationHelper.cs

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

namespace WebTest.Extensions
{
    /// <summary>
    /// Dados sobre a localização obtido da rota atual
    /// </summary>
    public class LocationData
    {
        public string ActionName { get; set; }

        public string ControllerName { get; set; }
    }

    public static class LocationHelper
    {
        public static LocationData GetLocationData<TModel>(this WebViewPage<TModel> page)
        {
            // TODO: validate page, ViewContext, RouteData, Values
            //      for:
            //          not null, contain values
            return new LocationData()
            {
                ActionName = (string)page.ViewContext.RouteData.Values["action"],
                ControllerName = (string)page.ViewContext.RouteData.Values["controller"]
                // TODO: get area name
            };
        }
    }
}

refer to it in View and use the static method as follows:

@using WebTest.Extensions
<div>
    <label>Action Name: </label>
    <output>@this.GetLocationData().ActionName</output>
</div>
<div>
    <label>Controller Name: </label>
    <output>@this.GetLocationData().ControllerName</output>
</div>

After this run the page, notice the results:

There are a few things to do:

  • Validates this extension as null values and also add the return of the Area.

Extra Points:

  • I did not make this example as a true ASP.NET Mvc Helper ... to create them you need to add the ASP.NET folder named App_Code (you can do this in the project context menu) and after that right click on this folder you can add a Helper (it creates a base code for you), the way to use it is absolutely the same, the difference is that this helper is more Razor-oriented.
06.10.2014 / 16:56