asp mvc routing with two optional parameters

You can’t have a route that has two optional parameters, only the last parameter can be optional precisely because of the problem you describe. I suggest that you have a default parameter for value, like byid and use this when the person selects a profession.

I assume that you’re constructing the URL via javascript, since using a GET form action would result in the parameter names being added to the URL. In this case, when the textbox is empty simply insert the default byid.

Update your route to include the default so any URLs that you generate will work. See Phil Haack’s blog post on this for an alternative way to handle generating URLs that have two “optional” parameters.

// used when both parameters are specified
routes.MapRoute(
        "Company+Profession", // Route name
        "{action}/{value}/{profId}", // URL with parameters
        new { controller = "Companies", action = "Index", value ="byid", profId = UrlParameter.Optional } // Parameter defaults
);

Leave a Comment