2

This question pertains to ASP.NET MVC 5.

I'm trying to use hyphens in my URLs by using route attributes, but I'm not having any luck getting it to work. I'm using this question and this MSDN blog reference. This URLs I want to have are:

/my-test/
/my-test/do-something

When I build my project and bring the page I'm testing up in a browser, I'm getting a 404 error. Here is the code I have so far:

// RouteConfig.cs
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();
        AreaRegistration.RegisterAllAreas();
        ...
    }
}

// MyTestController.cs - NOTE: THIS FILE IS IN AN AREA
[RouteArea("MyTest")]
[RoutePrefix("my-test")]
[Route("{action=index}")]
public class MyTestController : Controller
{
    [Route("~/do-something")]
    public JsonResult DoSomething(string output)
    {
        return Json(new
        {
            Output = output
        });
    }

    [Route]
    public ViewResult Index()
    {
        return View();
    }
}

// Index.cshtml
<script>
    $(document).ready(function () {

        // I'm using an ajax call to test the DoSomething() controller.
        // div1 should display "Hello, World!"
        $.ajax({
            dataType: "json",
            type: "POST",
            url: "/product-management/do-something",
            data: {
                output: "Hello, World!"
            }
        }).done(function (response) {
            $("div1").html(response.output);
        });
    });
</script>
<div id="div1"></div>

When I created the area, an area registration file was created and I had all my route information in that file, but according to the MSDN blog, I can remove that file and rely entirely upon the route attributes.

Community
  • 1
  • 1
Halcyon
  • 14,631
  • 17
  • 68
  • 99

1 Answers1

2

I figured it out. The class needed the following RouteAreaAttribute:

[RouteArea("MyTest", AreaPrefix = "my-test")]
public class MyTestController : Controller
{ 
    ...
}

This allowed me to delete the area route registration file too!

Halcyon
  • 14,631
  • 17
  • 68
  • 99