Miro
Miro

Reputation: 1806

Problem with giving id to action

I configured routes in Global.asax.cs like this:

routes.MapRoute("Post", "Post/Show/{PostId}", new { controller = "Post", action = "Show" });

and this is preview of used controller with action:

public partial class PostController : Controller
{
    public ActionResult Show(int PostId)
    {
        ...
    }
}

The problem is that it selects Show() action to use but it gives no int value,therefor it gives null.Here is an example of URL I used:../Post/Show/0

EDIT: When I configure my routes like this :

        routes.MapRoute("Post", "Post/Show/{id}", new { controller = "Post", action = "Show" });
        routes.MapRoute("Timeline", "{controller}/{action}/{Page}", new { controller = "Timeline", action = "List" });

everything works fine,but when I configure it like this:

        routes.MapRoute("Timeline", "{controller}/{action}/{Page}", new { controller = "Timeline", action = "List" });
        routes.MapRoute("Post", "Post/Show/{id}", new { controller = "Post", action = "Show" });

2nd route "Post" fails. Why ?!

Upvotes: 0

Views: 56

Answers (2)

Bobby
Bobby

Reputation: 1604

This should work just remember the order the routes appear in global.asax is very important too.

 routes.MapRoute(
                "Post", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Post", action = "Show", id = UrlParameter.Optional }  // Parameter defaults
            )

Upvotes: 1

Charles Ouellet
Charles Ouellet

Reputation: 6518

You should try:

routes.MapRoute("Post", "Post/Show/{PostId}", new { controller = "Post", action = "Show", PostId = UrlParameter.Optional });

Upvotes: 2

Related Questions