Muhammad Arslan Jamshaid
Muhammad Arslan Jamshaid

Reputation: 1197

Optional parameter at the end but still getting error

I have a very simple function in C# V.4 in this function page is a optional parameter i.e. I normally call mysite.com/product/PaginationOfProducts/20 but for some pagining control I have to call mysite.com/product/PaginationOfProducts/20?page=2 but on building my solution I am getting the error that optional parameters must appear after all required parameters

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

I don't understand how VS is deciding page is not my optional parameter even though I am defining it as a null-able int

Upvotes: 0

Views: 1214

Answers (2)

Colin Grealy
Colin Grealy

Reputation: 615

You need to give page a default value

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

Upvotes: 2

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

Quite simple, the error says it all. Change your method signature to

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

Thus, make sure that the optional parameter appears after the required parameters. page is not an optional parameter since it has no (explicit) default value, thus you cannot ommit it.

You could also change your method signature to

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

By doing so, the page parameter is an optional parameter as well.

Upvotes: 0

Related Questions