jim31415
jim31415

Reputation: 8818

ASP.NET MVC route parameter that may have hyphens

We have a working controller as shown below. The name parameter could be something like "Widget", "A09912", or "W-0-090-B". The routing fails when there is a hyphen in the parameter.

[HttpGet]
[Route( @"Product/{name:alpha}" )]
public ActionResult Index( string name )
{
    IList<Product> list = Repository.GetByName( name );
    return View( list );
}

Is there a way to configure things so that a hyphenated parameter will work?

Upvotes: 1

Views: 1011

Answers (1)

Nkosi
Nkosi

Reputation: 247571

Yes, there is a way to configure things so that a hyphenated parameter will work.

Remove the alpha constraint:

{x:alpha} Matches uppercase or lowercase Latin alphabet characters (a-z, A-Z)

By including hyphenated parameter it doesn't match the constraint you are currently using.

Have a look at Route Constraints in Attribute Routing in ASP.NET Web API 2

Upvotes: 2

Related Questions