C # MVC Route Definition

I need to call the client profile page, for example, "(www.mysite.com/John) or (www.mysite.com/customer name)"

so I added a route to be like that

routes.MapRoute(
              name: "Profile",
              url: "{id}",
              defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
             );

 routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

but it always goes to the first route, as if I need to open some kind of controller, it doesn’t work any tips?

Thank.

+4
source share
4 answers

the route will not work so that you have two options

1) When you go to any action yours URLshould be www.mysite.com/controller/action, otherwise it will give an errorHTTP 404

2) You can make the route unique by adding a prefix www.mysite.com/Customer/Johnlike this

  routes.MapRoute(
     name: "Profile",
     url: "Customer/{id}",
     defaults: new { controller = "Home", action = "Index"}
     );

and your actionshould be

public ActionResult Index(string id)
{
    string SurveyName = "";
    if (id != null)
        SurveyName = id;
    if (!string.IsNullOrEmpty(SurveyName))
    {
        ViewBag.Survey = SurveyName;
    }
    return View();
}
+1
source

controller action , - controller action.

Html.ActionLink . Html.ActionLink("action_name","Controller_name")

0

.

[EDIT] , , . , id = UrlParameter.Optional ( , URL- id).

            routes.MapRoute(
                      name: "Profile",
                      url: "{id}",
                      defaults: new { controller = "Employee", action = "Index"}
                     );

- , , , , (, ).

[OLD ANSWER] - .

The route below is only reached if the id parameter is a 4-digit value (you can use your own regular expression to meet your requirements).

            routes.MapRoute(
                      name: "Profile",
                      url: "{id}",
                      defaults: new { controller = "Employee", action = "Index"},
                      constraints: new { id = @"\d{4}" }
                     );
0
source

Make these changes. It worked for me.

routes.MapRoute(
              name: "Profile",
              url: "{id}",
              defaults: new { controller = "NewCon", action = "Demo", id = UrlParameter.Optional }
             );

 routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
-1
source

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


All Articles