Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current route in HtmlHelper?

Tags:

asp.net-mvc

A followup question to: Aggregate on dictionary question.

I used the Aggregate Linq functionality but perhaps there is a better, more clean way, to do it?

Can I get the current route from the HtmlHelper? Or what do you suggest? I want to make a language switcher so as when I am on a page/route and click another language the same action gets requested but with another language in the route.

Something like

EN/Home/Index and FR/Home/Index

like image 604
Nyla Pareska Avatar asked Jun 22 '10 09:06

Nyla Pareska


People also ask

What does HtmlHelper class do?

The HtmlHelper class renders HTML controls in the razor view. It binds the model object to HTML controls to display the value of model properties into those controls and also assigns the value of the controls to the model properties while submitting a web form.

What is MVC HtmlHelper?

What is HTML Helper in ASP.NET MVC 5? HTML Helpers are methods that return a string. Helper class can create HTML controls programmatically. HTML Helpers are used in View to render HTML content. It is not mandatory to use HTML Helper classes for building an ASP.NET MVC application.

How do I use TextBoxFor in HTML?

The HtmlHelper class includes two extension methods TextBox() and TextBoxFor<TModel, TProperty>() that renders the HTML textbox control <input type="text"> in the razor view. It is recommended to use the generic TextBoxFor<TModel, TProperty>() method, which is less error prons and performs fast.


1 Answers

You can easily retrieve the current route, or pieces of it. Assuming an HtmlHelper is your context as you say, it should look something like this:

public static MvcHtmlString SomeHelper(this HtmlHelper html) {
    RouteBase route = html.ViewContext.RouteData.Route;
    string action = html.ViewContext.RouteData.Values["action"].ToString();
    string controller = html.ViewContext.RouteData.Values["controller"].ToString();
    // ...
}
like image 97
Nathan Taylor Avatar answered Oct 04 '22 15:10

Nathan Taylor