简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM