Reputation: 14971
I'm trying to use route attributes in MVC 5. I created an empty MVC project in Visual Studio to experiment with and so far I can't get the routing to work. I'm using this page as a reference. I have the latest assemblies and updated all NuGet packages to their latest versions.
Here's my code:
// RouteConfig.cs
namespace MvcApplication1
{
using System.Web.Mvc;
using System.Web.Routing;
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Enables MVC attribute routing.
routes.MapMvcAttributeRoutes();
// The default route mapping. These are "out of the bag" defaults.
routes.MapRoute(null, "{controller}/{action}/{id}", new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
}
}
}
// TestControler.cs
namespace MvcApplication1.Controllers
{
using System.Web.Mvc;
public class TestController : Controller
{
public ContentResult Output1()
{
return Content("Output 1");
}
[Route("Test/Output2")]
public ContentResult Test2()
{
return Content("Output 2");
}
}
}
@* Index.cshtml *@
@Html.Action("Output1", "Test")
@Html.Action("Output2", "Test")
The Output1() method renders properly. However, when Output2() is rendered, I get the error "A public action method 'Output2' was not found on controller 'MvcApplication1.Controllers.TestController'."
Upvotes: 0
Views: 1080
Reputation: 323
This is because @Html.Action will not actually use routing. With it you explicitly specify actions and controllers.
The routing will be used when someone for instance makes the http://example.org/Test/Output2
request from a browser.
Upvotes: 1
Reputation: 2825
Your action is named Test2
not Output2
. Change the following
@Html.Action("Test2", "Test")
Upvotes: 8