Reputation: 425
I'm using .NET 3.5, MVC 2 and T4MVC 2.6.42...
I have the following action:
public virtual ActionResult Index(string id, int page = 1)
And the following route:
routes.MapRoute(
"Products", // Route name
"Products/{id}", // URL with parameters
new { controller = "Products", action = "Index", id = UrlParameter.Optional, page = UrlParameter.Optional }, // Parameter defaults
new string[] { "Web.Controllers" }
);
But when I try to call MVC.Products.Index("anything")
I get a "No overload for method 'Index' takes '1' arguments" exception. Calling MVC.Products.Index()
, however, works.
Shouldn't I be able to omit the "page" parameter since it defaults to '1'?
Note: I've tried defaulting the page parameter to 1 in the route, didn't work.
Note 2: Also tried the [Optional] Attribute with no success.
Upvotes: 3
Views: 1610
Reputation: 425
Like I said in my response to Kirk Woll above, apparently, optional parameters aren't supported in C# 3.0
I solved the problem by creating an overload and using the NonAction Attribute:
[NonAction]
public ActionResult Index(string id)
{
return Index(id, 1);
}
Then MVC.Products.Index("foo") works like a charm, with any C# version.
Upvotes: 0
Reputation: 43183
Though you figured out the problem with the wrong C# version, for future reference there is a way of doing this. You can write:
MVC.Products.Index().AddRouteValue("id", "anything");
This lets you add the value for individual param in addition to what the method call passes in.
Upvotes: 5
Reputation: 6911
Just make your int nullable and it will work.
public virtual ActionResult Index(string id, int? page = 1)
Upvotes: 0