Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action route optional id parameter

I'm trying to create a controller action with optional /id parameter like so:

  1. default http://localhost/tasks
  2. with id 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?

like image 633
Richard Mišenčík Avatar asked Jul 06 '15 22:07

Richard Mišenčík


1 Answers

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)
like image 106
BhavO Avatar answered Sep 26 '22 00:09

BhavO