没有参数的MVC4 ActionLink指向当前路径

时间:2016-10-17 12:37:08

标签: asp.net-mvc-4 iis actionlink html.actionlink

我有一个MVC4索引页面,其中包含以下链接:

$file = fopen("file.txt", "r");
$subject="Hey";
$txt="Hello...";
while(!feof($file)){
    $to = fgets($file);
    mail($to,$subject,$txt);
}
fclose($file);

但奇怪的是,两者都变成了指向 CURRENT 路径的超链接(即如果我们在 domain / Euro / 2016/1 都链接到此地址),而不是指向指定的控制器。

RouteConfig 中的一切正常:

@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)

控制器/操作存在且工作正常:

EuroController

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

导致这种奇怪行为的原因是什么?

修改

如果我传递年份参数,工作正常:public ActionResult Index(int? year, int? id) { ... } 正确指向域/ Mil / 666

1 个答案:

答案 0 :(得分:1)

我可以通过在默认路线之后添加此路线来使其正常工作。

 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 }
                 ); 

以下所有链接都会产生预期效果:

@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)
相关问题