最后的可选参数但仍然出错

Optional parameter at the end but still getting error

我在 C# V.4 中有一个非常简单的函数,在这个函数中 page 是一个可选参数,即我通常调用 mysite.com/product/PaginationOfProducts/20 但对于某些分页控件我必须调用 mysite.com/product/PaginationOfProducts/20?page=2 但在构建我的解决方案时,我收到 optional parameters must appear after all required parameters

的错误
public ActionResult PaginationOfProducts(int id = 0,  int ? page)
        {
// do something
}

我不明白 VS 如何决定 page 不是我的可选参数,即使我将它定义为 null-able int

很简单,错误说明了一切。 将您的方法签名更改为

public ActionResult PaginationOfProducts( int? page, int id = 0)

因此,请确保可选参数出现在必需参数之后。 page 不是可选参数,因为它没有(明确的)默认值,因此您不能省略它。

您也可以将您的方法签名更改为

public ActionResult PaginationOfProducts( int id = 0, int? page = null)

这样,页面参数也是一个可选参数。

您需要给页面一个默认值

public ActionResult PaginationOfProducts(int id = 0,  int? page = null)
{
    // do something
}