0

ASP.NET MVC 3 Routing confuses me. I feel like I've read everything I can, but sometimes, I still just don't get it. I am trying to create a URL that I can visit that looks like

/authorized/home/children/{childID}

I want that URL to show an HTML view that loads the contents for a specific child. My view is defined as follows:

/Views/Authorized/Home/Children/Child.cshtml

In my global.asax.cs file, I have added the following route:

  routes.MapRoute(
    "Child", // Route name
    "{controller}/Home/Children/{action}/{id}",
    new { controller = "Authorized", action = "Child", id = UrlParameter.Optional }
  );

In AuthorizedController.cs, I have the following:

public ActionResult Child(string id)
{
  return View("~/Views/Authorized/Home/Children/Child.cshtml");
}

If I visit /authorized/home/children, I see the contents of Child.cshtml. However, if I visit /authorized/home/children/1, I get a 404.

What am I doing wrong? Thank you

2
  • 2
    Is this the only route you have defined? if not can you please post the rest of the routes? Commented Aug 8, 2012 at 13:23
  • All other routes have been commented out in an attempt to isolate the problem. The route registered above is the only route that is defined. Commented Aug 8, 2012 at 13:29

1 Answer 1

2

The route you shared does not match the route you're saying you're wanting.

You want:

/authorized/home/children/{childID}

But, you're route is expecting:

/Authorized/Home/Children/{action}/{id}

Note the additional action parameter there. Is children your action in your controller, or is it child? If it's children you should update your route to this:

 routes.MapRoute(
    "Child", // Route name
    "{controller}/Home/{action}/{id}",
    new { controller = "Authorized", action = "Children", id = UrlParameter.Optional }
  );

However, if it's Child you'll need to remove the {action} from your route like this:

 routes.MapRoute(
    "Child", // Route name
    "{controller}/Home/Children/{id}",
    new { controller = "Authorized", action = "Child", id = UrlParameter.Optional }
  );

This will make an explicit route, directing to the Child action.

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

2 Comments

Sorry, I copied the wrong code from a second project I had open. I have since updated my post.
Does the second route provided by @Mark Oreta solve your problem though? because it looks like it should.

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.