Mike Bailey
Mike Bailey

Reputation: 12817

Route with nullable parameters showing up with query string for null route value

I have the following controller action:

public class Foo
{
    public ActionResult Bar(int? barId)
    {
        ...
    }
}

The corresponding route for this action is given by:

routes.MapRoute("Foobar", "bar/{barId}",
                new { controller = "Foo", action = "Bar", barId = UrlParameter.Optional },
                new { barId = @"^[0-9]+$" });

In my views, I'm generating routes as:

@Url.Action("Bar", "Foo", new { barId = bar.BarId })

For bar.BarId = 32, I receive the expected URL of /Foo/32

But I would also like to generate routes for null values as:

@Url.Action("Bar", "Foo", new { barId = (int?)null })

Except, for this I receive the URL of /Foo?barId=currentBarId

Where currentBarId is the barId of whatever Bar page I'm currently viewing.

What am I doing wrong?

Upvotes: 0

Views: 567

Answers (1)

Dima
Dima

Reputation: 6741

Change your constraint on:

new { barId = @"^[0-9]*$" }

this will allow empty barId for this route.

Upvotes: 1

Related Questions