Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of RouteData.GetRequiredString in ASP.NET 5

I have several HtmlHelper extension methods that I use to create navbar buttons - one is for a context-sensitive help link. In my extension method I need to know the name of the current controller and action e.g.:

var currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
var currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");

What can I use in ASP.NET 5 to get this information since there is no GetRequiredString() method on RouteData anymore?

like image 224
Keith Hill Avatar asked May 19 '15 23:05

Keith Hill


People also ask

What is RouteData in MVC?

RouteData is a property of the base Controller class, so RouteData can be accessed in any controller. RouteData contains route information of a current request. You can get the controller, action or parameter information using RouteData as shown below. Example: RouteData in MVC.


1 Answers

You could create an extension yourself.

namespace Microsoft.AspNet.Mvc
{
    public static class HelperExtensions
    {
        public static string GetRequiredString(this RouteData routeData, string keyName)
        {
            object value;
            if(!routeData.Values.TryGetValue(keyName, out value))
            {
                throw new InvalidOperationException($"Could not find key with name '{keyName}'");
            }

            return value?.ToString();
        }
    }
}
like image 94
Kiran Avatar answered Sep 25 '22 19:09

Kiran