James
James

Reputation: 730

MVC3 routing issue with nullable parameter

I have an odd issue. I have a controller action which takes a couple of optional parameters

Function Index(sectionID As Integer?, title As String) As ActionResult

    Return View()
End Function

I then have added a specific route for this action method so that we get pretty urls for this page

routes.MapRoute( _
        "By_Section", _
        "home/{sectionID}/{title}", _
        New With {.controller = "Home", .action = "Index", .sectionID = Nothing},
        New With {.sectionID = "\d+"}
        )

This all works. However, when I am on a page where the sectionID is set (for example http://localhost/home/index/1/test), the following piece of code produces an odd output.

<%= Url.Action("Index", "Home")%>

Instead of showing http://localhost/home/index as you might expect, it shows http://localhost/home/index/1/test. So it appears it is picking up the sectionID and title from the current url and automatically inserting them into the Url.

How can I prevent this from happening?

Thanks

James

Upvotes: 0

Views: 262

Answers (1)

devdigital
devdigital

Reputation: 34349

Yes, this is expected behaviour, the routing system will reuse parameter values from the current request if you haven't provided a new value explicitly. The best option when rendering links is to specify explicit values for all of your routing parameters.

<%= Url.Action("Index", "Home", new { sectionID = (int?)null }) %>

Upvotes: 1

Related Questions