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.

2
  • What does it mean - "testing in browser"? Commented Apr 22, 2015 at 20:20
  • I was testing my code in a browser to see it my route attributes were working. Commented Apr 22, 2015 at 20:32

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.