I'm trying to create a controller action with optional /id parameter like so:
http://localhost/tasks
http://localhost/tasks/42
Here is the controller and the action: What I tried to do was to use the route attribute on the action
public class TasksController : AsyncController
{
[Route("tasks/{id}")]
public ActionResult Index(string id)
{
...
}
}
This worked but only with the id parameter set in the url, but the default page /tasks
throws a not found error, alternatively when using [Route("tasks")]
without the id, the default page works, but when id is set, a not found error is thrown again. I also tried [Route("tasks/{id ?}")]
to mark the id as optional parameter but it didn't work.
Any ideas how to make this work?
You can make a URI parameter optional by adding a question mark to the route parameter. If a route parameter is optional, you must define a default value for the method parameter.
Set the default value on the action method and add question mark to end of route param.
[Route("tasks/{id?}")]
public ActionResult Index(string id =null)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With