2015-04-22 27 views
2

这个问题涉及到ASP.NET MVC 5使用路由属性在ASP.NET MVC 5随着地区

我试图通过使用路由属性用在我的网址连字符,但我没有任何运气得到它的工作。 I'm using this questionthis MSDN blog reference.这个网址我想有是:

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

当我建立我的项目,并把我在浏览器中测试的页面中,我得到一个404错误。这里是我的代码至今:

// 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> 

当我创建的区域,一个区域的注册文件被创建,我不得不在该文件中所有的路由信息​​,但根据MSDN博客中,我可以删除文件并完全依赖路由属性。

+0

这是什么意思 - “在浏览器中测试”? –

+0

我在浏览器中测试我的代码,看看我的路由属性是否正常工作。 – Halcyon

回答

1

我想通了。该类需要以下RouteAreaAttribute:

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

这也允许我删除区域路由注册文件!