MiscellaneousUser MiscellaneousUser - 1 month ago 9
ASP.NET (C#) Question

ASP.NET MVC Optional Page Parameter

Lets say I've two web addresses

http://www.example.com/page/one
http://www.example.com/page/one/subOne


How do I get them to be handled by the same controller. At the moment the top address is being handled but the second is being handled by the postback function which doesn't render the page.

So for my routes config, I have

routes.MapRoute("PageRule", "page/{id}", new { Controller = "document", action = "Index", id = UrlParameter.Optional });
routes.MapRoute("Page2Rule","page/{id}/{misc}", new { Controller = "document", action = "Index", id = UrlParameter.Optional });


and in the controller I have

// GET: Document
public ActionResult Index(string id, string misc )


and

// Post
[HttpPost]
public ActionResult postcomment(string gCaptcha,string txtName, string txtEmail, string txtMessage)

Answer

I suspect this might be the only route you need:

routes.MapRoute("PageRule",
                "page/{id}/{misc}",
                new
                {
                    Controller = "document",
                    Action = "Index",
                    misc = UrlParameter.Optional
                });

Notice that there is no optional for id. The key is that both id and misc cannot be optional at the same time - only the last parameter in the route can be optional