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.

4
  • Probably not the issue, but only the last parameter can be marked as UrlParameter.Optional Commented Oct 17, 2016 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. Commented Oct 17, 2016 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) Commented Oct 17, 2016 at 14:13
  • @Nkrosi Neither of the two links you suggested worked. Commented Oct 17, 2016 at 17:36

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.