Second MapRoute in asp.net MVC 4 doesn't work with parameters

I want to add a second MapRoute to my first MVC 4 Project and I added this code to Global.asax.vb

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
    routes.MapRoute( _
        "Math", _
        "Calculator/{action}/{foo}/{intBar}", _
        New With {.controller = "Calculator", .action = "Add", .foo = ""} _
    )
    routes.MapRoute( _
        "Default", _
        "{controller}/{action}/{id}", _
        New With {.controller = "Default", .action = "Index", .id = ""} _
    )

      

and this is my controller /Controllers/CalculatorController.vb

   Function Add(         ByVal foo     As String, 
                Optional ByVal intBar? As Integer = 1) As ActionResult
        ViewData("Message") = foo & " Welt"
        Return View()

    End Function

      

Now my problem is, what am I doing wrong?

localhost: 18118 / Calculator / Add / Hallo - Post only "Welt", but where is "Hallo"?

localhost: 18118 / Calculator / Add / Hallo / 7 - Error 404? What for?

Hope you can help / teach me. Thank you for your time!

+3


source to share


2 answers


The problem is caused by your two routes "Math" and "Default" defining different parameters named When you call:

localhost: 18118 / Calculator / Add / Hallo

Then the Default route and named parameters are used:

  • controller = calculator
  • action = Add
  • id = Hallo


But your Action Add

needs a parameter named foo

. I would suggest renaming the foo parameter in the "Math" route mapping as id :

 routes.MapRoute( _
        "Math", _
        "Calculator/{action}/{id}/{intBar}", _ ' foo renamed to id
        New With {.controller = "Calculator", .action = "Add", .id = ""} _
    )

      

And rename the Action: parameter as well Function Add(ByVal id As String,...

to make it work.

NOTE: renaming is a suggestion to make it work without saying that this is the best way how to do it ...

+1


source


I think this is because you are overriding the parameter foo

from the url with the operator .foo = ""

in the default object. You are matching {foo}

in your route, so it takes the string "Hallo", but then you replace it with an empty string.



Try to retrieve .foo = ""

from the default object.

0


source







All Articles