How to change controller text in ASP.NET MVC URL?

Recently, I was asked to change the small asp.net mpc application so that the name of the control in the URLs contains a dash. For example, when I created a controller named ContactUs with View named Index and Sent, the URLs would be http://example.com/ContactUs and http://example.com/ContactUs/Sent . The person who asked me to make changes wants the URLs to be http: // example / contact-us and http://example.com/contact-us/sent .

I do not believe that I can change the name of the controller because '-' will be an invalid character in the class name.

I was looking for an attribute that could apply to a controller class that would allow me to specify a string in which the controller will use int url, but I have not found it yet.

How can i do this?

+3
source share
4 answers

Just change the URL used in the route itself to point to an existing controller. In your Global.asax:

routes.MapRoute(
  "Contact Us",
  "contact-us/{action}/",
  new { controller = "ContactUs", action = "Default" }
);
+9
source

I do not believe that you can change the display name of the controller. In the beta version, the controller was created using the controller route data with the controller suffix. This may have changed in RC / RTM, but I'm not sure.

"contact-us/{action}" : new { controller = "ContactUs" }, , .

+2

. Global.asax :

public static void RegisterRoutes(RouteCollection routes)
{
  ...
  routes.MapRoute(
    "route-name", "contact-us/{action}", // specify a propriate route name...
    new { controller = "ContactUs", action = "Index" }
  );
  ...

, sent . url .../sent, Index.

, RouteCollection. , .

+1

ASP.NET MVC , Iconic. , , , haacked. MVC.

EDIT: I see you can use custom routes, but this is probably not the best solution in this case. Is there really a way to deal with {controller}before displaying it? If it were possible, you could replace all the characters with a "-".

0
source

Source: https://habr.com/ru/post/1706978/


All Articles