ASP.NET MVC : Empty ActionLinks appearing

2020-03-28 02:01发布

问题:

I'm using a default route, so that I don't need to specify the controller.

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

With this, I can create URLs like myapp.com/Customers rather than myapp.com/Home/Customers

When I test locally, everything is fine. When I upload a live version, any links generated with Html.ActionLink are empty. I know I'm using Html.ActionLink correctly, because it works fine locally:

//                   Title                 Action      Controller
<%: Html.ActionLink("Manage My Settings", "Settings", "Home") %>

I've removed all routes but the default, tried specifying ActionLink with and without the controller etc. I even tried reverting to having the controller in the route, e.g:

"{controller}/{action}/{id}"

Nothing works live. Everything works locally. Going slightly mad.

UPDATE:

OK, made a strange discovery. I actually had another optional UrlParameter after id, called page. I stupidly didn't include it in the example because I thought it made no difference. If I take it out, things seem to work.

So, actually, this works:

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

and this works!

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

but this does Not work

routes.MapRoute(
   "Default", 
   "{action}/{id}/{page}", 
    new { controller = "Home", action = "Index", 
    id = UrlParameter.Optional, page = UrlParameter.Optional }
);

Why Not?

回答1:

Found the answer! There's a bug in MVC3 when using two consecutive optional UrlParameters, as detailed by Phil Haack, here routing-regression-with-two-consecutive-optional-url-parameters

You need to first declare a version of the route with only one optional parameter. So

routes.MapRoute(
    "Default", // Route name
    "{action}/{id}", // URL with ONE parameter
    new { controller = "Home", action = "Index", 
    id = UrlParameter.Optional } // Parameter defaults
);

routes.MapRoute(
    "Default_with_page", // Route name
    "{action}/{id}/{page}", // URL with TWO parameters
    new { controller = "Home", action = "Index", 
    id = UrlParameter.Optional, page = UrlParameter.Optional } 
    // Parameter defaults
);

Seems really obvious now. If I'd actually included all the details I'm sure Serghei or someone else would have seen the problem, so thanks for all the help guys!



回答2:

look at the article in which is explayned how to deploy ASP.NET MVC Application on IIS6