3

I have a MVC4 Index page that have the following links:

@Html.ActionLink("FOO", "Index", "Mil", new { year = String.Empty, id = String.Empty }, null)
@Html.ActionLink("BAR", "Index", "Euro", new { year = String.Empty, id = String.Empty }, null)

But oddly both turn into a hyperlink to the CURRENT path (i.e. if we are at domain/Euro/2016/1 both link to this address), instead of pointing to the specified controller.

Everything normal in RouteConfig:

routes.MapRoute(
             name: "Default",
             url: "{controller}/{year}/{id}",
             defaults: new { controller = "Home", action = "Index", year = UrlParameter.Optional, id = UrlParameter.Optional }
         );

The Controllers/Actions exist and work fine:

EuroController:

public ActionResult Index(int? year, int? id)
 {
    ...
 }

What can be causing this odd behavior?

EDIT:

If i pass year parameter, works fine: @Html.ActionLink("FOO", "Index", "Mil", new { year = 666, id = String.Empty }, null) correctly points to domain/Mil/666.

Mr Billy
  • 151
  • 1
  • 2
  • 13
  • Probably not the issue, but only the last parameter can be marked as `UrlParameter.Optional` –  Oct 17 '16 at 12:39
  • I edited my question. That's not the solution but surely is related. I changed `year=UrlParameter.Optional` in Routes to `year=""` as you suggested but the problem remained. – Mr Billy Oct 17 '16 at 13:34
  • either use `null` ie: `@Html.ActionLink("FOO", "Index", "Mil", new { year = null, id = null }, null)` or remove them all together, ie: `@Html.ActionLink("FOO", "Index", "Mil", null, null)` – Nkosi Oct 17 '16 at 14:13
  • @Nkrosi Neither of the two links you suggested worked. – Mr Billy Oct 17 '16 at 17:36

1 Answers1

2

I was able to make it work by adding this New route after the Default one.

 routes.MapRoute(
                name: "Default",
                url: "{controller}/{year}/{id}",
                defaults: new { controller = "Home", action = "Index", year = "", id = UrlParameter.Optional }
                 );
 routes.MapRoute(
                name: "New",
                url: "{controller}/{year}",
                defaults: new { controller = "Home", action = "Index", year = UrlParameter.Optional }
                 ); 

All the following links produce the desired effect:

@Html.ActionLink("Euro 2014", "Index", "Euro", new { year = 2014 }, null)
@Html.ActionLink("Euro 2015", "Index", "Euro", new { year = 2015, id = String.Empty }, null)
@Html.ActionLink("Euro 2016", "Index", "Euro", new { year = DateTime.Now.Year, id = "" }, null)
@Html.ActionLink("Back to Euro", "Index", "Euro", new { year = String.Empty }, null)
Mr Billy
  • 151
  • 1
  • 2
  • 13