Pergunta

i want to add a second MapRoute to my first MVC 4 Project, well i added this code in 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, what i am doing wrong?

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

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

I hope you can help/teach me. Thanks for your time!

Foi útil?

Solução

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

localhost:18118/Calculator/Add/Hallo

Then the "Default" route is used and named parameters are:

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

But your Action Add requires parameter named foo. I would suggest, rename 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 working.

NOTE: renaming is suggestion to make it working, not saying that this is the best way how to do that...

Outras dicas

I think it's because you're overriding the foo param from the URL with the .foo = "" statement in the defaults object. You map {foo} in your route, so it takes in your 'Hallo' string -- but then you replace it with the empty string.

Try taking out .foo = "" from your defaults object.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top