Ernesto Lacalle
Ernesto Lacalle

Reputation: 1

I can't get the parameter in MVC 5

I created a custom route for my controller but when i pass the parameter in the url i can't get the variable in the controller class the ouput is empty.

The route

routes.MapRoute(
           "Employee", "Employee/{name}", new
           {controller = "Employee", action = "Search", name = UrlParameter.Optional}
);

Class EmployeeController

    public ActionResult Search(string name)
    {
        var input = Server.HtmlEncode(name);
        return Content(input);
    }

Upvotes: 0

Views: 488

Answers (1)

trashr0x
trashr0x

Reputation: 6565

Firstly, your custom route needs to come before the default one so it matches first:

routes.MapRoute(
    name: "Employee",
    url: "Employee/{name}", 
    defaults: new { controller = "Employee", action = "Search", name = UrlParameter.Optional }
);

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

Since you defined the route URL to "Employee/{name}", and having a public ActionResult Search(string name) action signature in EmployeeController, you should be able to match using the following formats:

  • /Employee/George
  • /Employee?name=George

Both will return "George".

Upvotes: 3

Related Questions