I'm having an odd issue with routing in a basic ASP/MVC project.
I have a bunch of nav items setup:
<li><a href="@Url.Action("index", "home")">Home</a></li>
<li><a href="@Url.Action("fire", "home")">Fire</a></li>
<li><a href="@Url.Action("law-enforcement", "home")">Law Enforcement</a></li>
<li><a href="@Url.Action("forensics", "home")">Forensics</a></li>
<li><a href="@Url.Action("reconstruction", "home")">Reconstruction</a></li>
They all work fine, except for the third one, labeled law-enforcement
.
When I mouse over this item, the URL is: http://localhost:54003/home/law-enforcement
When I mouse over any other item, the URl is: http://localhost:54003/fire
My Controller setup is:
public ActionResult Index()
{
return View();
}
[Route("~/fire")]
public ActionResult Fire()
{
return View();
}
[Route("~/law-enforcement")]
public ActionResult Law()
{
return View();
}
[Route("~/forensics")]
public ActionResult Forensics()
{
return View();
}
[Route("~/reconstruction")]
public ActionResult Reconstruction()
{
return View();
}
And my route config is:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapMvcAttributeRoutes();
routes.MapRoute("Default", "{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
}
When I go to the route the URL specifies, ASP responds with a 404 page not found (as it should). If I go to the route that I know it should be, such as localhost/law-enforcement
then the correct View is rendered.
Any ideas why ASP is routing this one particular action incorrectly?
You can keep your url mapping in either of 2 ways as below:
One way is to decorate your actionresult
with attribute as below:
// eg: /home/show-options
[Route("law-enforcement")] //Remove ~
public ActionResult Law()
{
return View();
}
As per docs
otherwise
Just add one more configuration in Route.config
file
routes.MapRoute("SpecialRoute", "{controller}/{action}-{name}/{id}",
new {controller = "Home", action = "law-enforcement", id = UrlParameter.Optional}
);