Optional Route ID parameter

I am trying to create a controller action with an optional / id parameter, for example:

  • default http://localhost/tasks
  • with identifier http://localhost/tasks/42

Here is the controller and the action: I tried using the route attribute for the action

public class TasksController : AsyncController
{
    [Route("tasks/{id}")]
    public ActionResult Index(string id)
    {
        ...
    }
}

This worked, but only with the id parameter specified in the URL, but the default page /tasksthrows an error not found, alternatively when using [Route("tasks")]without id, the default page works, but when the identifier is set, the error was not found again. I also tried [Route("tasks/{id ?}")]marking id as an optional parameter, but it did not work.

Any ideas how to make this work?

+5
source share
3 answers

URI , . , .

.

[Route("tasks/{id?}")]
public ActionResult Index(string id =null)
+7

:

public class PlansController : AsyncController
{
    [Route("tasks/{id}")]
    public ActionResult Index(string id)
    {
        if(id == null)
        {
             return View("ViewName");
        }
        else
        {
             //Query DB and get model for the view
             return View("ViewName", Model);
        }
    }
}

, , .

0
public class TestController : AsyncController
{
    [Route("tasks/{id?}")]
    public ActionResult Index(string id)
    {
        return new ContentResult() { Content = id ?? "Empty" };
    }

    [Route("task/{id=demo}")]
    public ActionResult Task(string id)
    {
        return new ContentResult() { Content = id ?? "DemoEmpty" };
    }
}

I just test it, it works great

-1
source

All Articles