Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Handling nested action methods?

I've got a Project class which contains one or more issues:

public class Project
{
    public int Id {get; set;}
    public string Name {get; set;}
    public List<Issue> Issues {get; set;}
}

public class Issue
{
    public int Id {get; set;}
    public string Description {get; set;}
}

I'm having trouble structuring my mvc app so that the Issues are a sub item of projects on the URL routes?

/projects/details/1/issues/ - Display list of project issues
/projects/details/1/issues/1 - Display issue #1
/projects/details/1/issues/2 - Display issue #2
/projects/details/1/issues/create/ - Create a new issue for project #1

My initial thoughts is to create a route which leads to the following Action Method

public ActionResult Details(int projectId, string action)
{
    if(action =="issues")
    {
      //Call ActionMethod...
    }
}

But it just doesn't feel right. Any suggestions? Is it true that something like this possible with RoR?

like image 912
Fixer Avatar asked Feb 06 '26 08:02

Fixer


1 Answers

You can provide a route for that action like this:

routes.MapRoute("ProjectIssues",
                "projects/{projectID}/issues/{issueID}",
                new { controller=Projects, action=Details});

Then requests like http://domain.com/projects/3/issues/5 would be mapped to your Details action in ProjectsController.

You can get the parameters with the same parameter names in route

public ActionResult Details(int projectID,int? issueID)
{
    if(issue.HasValue)
    {
        return RedirectToAction("IssueDetails",new {ProjectID=projectID,IssueID=issueID});
    }
    else
    {
        return RedirectToAction("AllIssues",new {ProjectID=projectID});
    }

}
like image 53
Ufuk Hacıoğulları Avatar answered Feb 09 '26 02:02

Ufuk Hacıoğulları