0

I've looked through the various questions already asked on this topic, and I've spent time trying to get it working how I would like it to, but I haven't had much luck so hopefully someone here can help me fill in the gaps.

With a new site I'm creating I wanted to try getting the URL structure to be more RESTful (I wanted to do it with my first MVC3 creations, but, time did not permit such experimenting). However, I don't want the different URLs to all point to the same action. I want different actions for each resource requested to keep the controller code concise and intuitive.

Here is an example of the URL structure I'm shooting for:

/Case   //This currently works
/Case/123   //This currently works
/Case/123/Comment   //This one does not work (404)

Here is how I currently have my routes setup:

routes.MapRoute(
    "Case",
    "Case/{id}",
    new { controller = "Case", action = "Number" }
);

routes.MapRoute(
    "CaseComment",
    "Case/{caseId}/Comment/{id}",
    new { controller = "Case", action = "CaseComment" }
);

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

The first two URL's I listed are worked correctly with this route structure. The first URL takes me to my listing page. When an id is specified, I hit the Number action so I can show details for that particular record. The Comment URL is not working.

I have the action for the third URL defined as:

public ActionResult CaseComment(string caseId, string id) {
    //Narr
}

What am I missing? And, could I set this up in an easier fashion for future resources?

4 Answers 4

1

I believe MapRoutes are order specfic, so

/Case/123/Comment 

is using your

routes.MapRoute( 
  "Case", 
  "Case/{id}", 
  new { controller = "Case", action = "Number" }); 

route, thus throwing a 404. Most specific route should be place above more general routes.

Sign up to request clarification or add additional context in comments.

Comments

0

Try placing the CaseComment route above the Case route.

Comments

0

Mapping routes are order specific.

One thing you may wish to consider for restful routing in MVC is a project called RestfulRouting that is on GitHub originally written by Steve Hodgekiss.

https://github.com/stevehodgkiss/restful-routing

If nothing else, looking at the code may well help you.

Hope this helps.

Comments

0

I needed to make the id parameter optional.

routes.MapRoute(
    "Case Resources",
    "Case/{caseId}/{action}/{id}",
    new { controller = "Case", action = "CaseComment", id = UrlParameter.Optional }
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.