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?
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.
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With