Search code examples
asp.net-mvcasp.net-mvc-routing

Attribute routing unexpected behavior on views outside specific action.


As an example I have two actions on one controller. The actions both use attribute routing.

[Route("proofCampaign/{campaignId?}", Name ="Route1")]
public ActionResult ProofCampaign(int campaignId){
            //Do stuff
            return View{campaignVM}
            }
[Route("proofOrder/{orderId}", Name ="Route2")]
public ActionResult ProofOrder(int orderId){
            //Do stuff
            return View{orderVM}
            }

When I use @Url.RouteUrl("Route1") on any view I get the proper url but when I try to use @Url.RouteUrl("Route2") on any view I get a null.

However when I go to the actual page/view that Route2 leads to it returns the expected url.

The difference in the above code is the "?" in the route, even though the parameter is not optional. Ultimately I want to display the second link on other views as part of a menu.

Why does the route not show up without putting in the optional param indicator?


Solution

  • Because orderId is not optional you need to include it in the Url

    @Url.RouteUrl("Route2", new { orderId = xxx })