Search code examples
c#asp.net-mvcasp.net-mvc-5asp.net-mvc-routing

Can I have a route with generic parameter name


I am working on ASP.Net MVC routing. I want to create a route that passes the param to action, irrespective of param name. I have done some reading about this and tried different options, but cannot get it working, so want to know if this is possible?

Here is my question with an example:

I have two action methods, in my StudentController

// First Action in StudentController
public ActionResult GetStudentByName(string name)

// Second Action in StudentController
public ActionResult GetStudentById(int id)

Now in my route config I have:

// Get Student By Name
routes.MapRoute(
   name: "StudentByName",
   url: "Student/GetStudentByName/{name}",
   defaults: new { controller = "Student", action = "GetStudentByName", name = "" }
);

// Get Student By Id
routes.MapRoute(
    name: "StudentById",
    url: "Student/GetStudentById/{id}",
    defaults: new { controller = "Student", action = "GetStudentById", id = UrlParameter.Optional }
    );

This works fine, but I have to define two routes for the two actions. My actions are expecting parameters with different names (name and id).

I want a generic route, that handles both Action method and passes the parameter to action, something like this?

// Is this possible?
routes.MapRoute(
    name: "AspDefault",
    url: "{controller}/{action}/{GenericParamName}",
    defaults: new { controller = "Home", action = "Index", GenericParamName = UrlParameter.Optional }
);

I have tried this, but cannot get it working. If the parameter name in Action and Route don't match, they don't seem to be passed through...

Is it possible to handle these two action methods with one route? if so how?


Solution

  • Is it possible to handle these two action methods with one route? if so how?

    You would need to name the parameter on both actions the same to match the route

    For example.

    //Student/GetStudentByName/JDoe
    //Student/GetStudentById/13456
    routes.MapRoute(
        name: "StudentDefault",
        url: "Student/{action}/{value}",
        defaults: new { controller = "Student", value = UrlParameter.Optional }
    );
    

    The above route would mean that the controller actions would have to be updated to

    public class StudentController : Controller {
    
        // First Action in StudentController
        public ActionResult GetStudentByName(string value) {
            //...
        }
    
        // Second Action in StudentController
        public ActionResult GetStudentById(int value) {
            //...
        }
    
    }