ASP.NET MVC C# Routing - Passing a null integer

怎甘沉沦 提交于 2020-01-04 02:11:06

问题


I'm working with MVC 3 in a web app and i'm facing a problem in routing.

I'm defining my router handler like this:

           routes.MapRoute(
           "Users", 
           "{controller}.aspx/{action}/{id}/{page}", // URL with parameters
           new { controller = "Users", action = "Details", id = UrlParameter.Optional, page = UrlParameter.Optional } // Parameter defaults
       );

The url is: http://app.domain/Users.aspx/Details/114142/5 (example)

I'm sucefully getting the id of the user, but i can't get the page number.

The controller of users is initialized like this:

           public ActionResult Details(long id, int? page)

The page is always returning null (i need the page as a null integer).

And i defining the route wrong?

Thanks


回答1:


id cannot be optional if page is optional. Only the last parameter of a route definition can be optional.

So :

routes.MapRoute(
    "Users", 
    {controller}.aspx/{action}/{id}/{page}",
    new { 
        controller = "Users",  
        action = "Details", 
        page = UrlParameter.Optional 
    }
);

and then: /Users.aspx/Details/114142/5 will successfully map to

public ActionResult Details(long id, int? page)
{
    ...
}



回答2:


You are using a wrong URL. Try this:

http://app.domain/Users.aspx/Details/114142?page=5


来源:https://stackoverflow.com/questions/5436031/asp-net-mvc-c-sharp-routing-passing-a-null-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!