开发者

Default value for parameter in Controller Method is overriding everything

开发者 https://www.devze.com 2023-01-13 10:18 出处:网络
Hello i have just started learning mvc2 and im having a problem with the default value for the parameter page(you can see the method below).

Hello i have just started learning mvc2 and im having a problem with the default value for the parameter page(you can see the method below).

Its always 0 regardless of what i type in the URL. For example this

h.ttp://localhost:52634/Products/List/2

should show page 2 but when in debug mode the page parameter is 0, so im always getting the first page of the list in my view.

i am using the predefined standard routes in global asax when you start a new mvc2 project.

am i missing something?

//This is the ProductsController

   public ViewResult List(int page = 0)
    {

        var products开发者_如何学运维 = productsRepo.Products()

   //send in source, current page and page size
        productList = new PagedList<Product>(products, page, 10);

        return View(productList);
    }


It's a routing issue, the default route specifies an id property, you're using a property called page. I'm new to MVC myself, but add this route before the default route:

routes.MapRoute("MyRoute", "{controller}/{action}/{page}",
    new { controller = "Foo", action = "List", page = UrlParameter.Optional });


Remove the " = 0", and do:

public ViewResult List(int? page)
{
    int val = page.GetValueOrDefault(0);

And use val everywhere instead of page. That should work. If not, it's an issue with routing.

HTH.


I know it's very late to answer. As default route for MVC is following

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

which is expecting that parameter name should be id. Now you have 2 options here either change your parameter name to id or the other option is define your own route in route.config file which is under App_Start folder.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号