开发者

MVC MapRoute not routing with required parameter

I'm wanting the URL to my MVC application to be like:

www.site.com/Bob

Which would in turn 'redirect' to Home/Details/Bob.

I've set up the following MapRoute:

    routes.MapRoute( _
Nothing, _
"{personName}", _
New With {.controller = "Home", .action = "Details", .personName = ""}, _
New With {.result = New NameConstraint()} _
)

The NameConstraint is an IRoutingConstraint that checks to see the name exists. If it does it return true, else returns false which causes it to the go to the second (and default) MapRoute.

Public Class ListingConstraint
    Implements IRouteConstraint
    Public Function Match(ByVal httpContext As System.Web.HttpContextBase, ByVal route As System.Web.Routing.Route, ByVal parameterName As String, ByVal values As System.Web.Routing.RouteValueDictionary, B开发者_开发百科yVal routeDirection As System.Web.Routing.RouteDirection) As Boolean Implements System.Web.Routing.IRouteConstraint.Match
        Dim personName As String
        personName = CStr(values("personName"))
        If listingName = "Bob" Then  'akin to checking the database for a valid name
            Return True
        Else
            Return False
        End If
    End Function
End Class

The problem arises when I call: www.site.com/Bob. It correctly routes to the Home/Details code in the controller, but the supplied parameter is nothing.

E.g. Function Details(ByVal id As String) As ActionResult Dim viewModel As New XViewModel(id) Return View(viewModel) End Function

The value of id is set to nothing, and not Bob as expected.

Any ideas?


Try this:

 New With {.controller = "Home", _
.action = "Details", _
.personName = UrlParameter.Optional}, 

in your maproute

PS: Luckily my name is not Home ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜