ASP.NET MVC 3 和静态路由

发布于 2024-12-20 10:33:07 字数 2473 浏览 1 评论 0原文

我有一个 ASP.NET MVC 3 应用程序。我正在尝试实现 http://www.slideshare.net/calamitas 中找到的路由标准/宁静的最佳实践。我使用幻灯片 15 和 17 作为参考。我知道这个幻灯片是关于 RAILS 的。然而,这种语法看起来更干净、更自然。这就是我想使用它的原因。

我已在控制器中成功实现了索引和显示操作。但是,我在执行“创建”和“更新”操作时遇到问题。此时,当我引用其中任何一个时,我都会收到 404。目前,我的控制器如下所示:

public class OrdersController : Controller
{
    // GET: /Orders/
    public ActionResult Index()
    {
        var results = new[] {
            new {id=1, price=1.23, quantity=2}
        };
        return Json(results, JsonRequestBehavior.AllowGet);
    }

    //
    // GET: /Orders/{orderID}
    public ActionResult Show(int id)
    {
        string result = "order:" + id;
        return Json(result, JsonRequestBehavior.AllowGet);
    }

    //
    // POST: /Orders/{order}
    [HttpPost]
    public ActionResult Create(object order)
    {
        var message = "The order was successfully created!";
        return Json(message);
    }

    //
    // PUT: /Orders/{orderID}
    [HttpPut]
    public ActionResult Update(object orderID)
    {
        var message = "The order was successfully updated!";
        return Json(message);
    }
}

当我注册路由时,我使用以下内容:

context.MapRoute(
    "OrderList",
    "Orders",
    new { action = "Index", controller="Orders" }
);

context.MapRoute(
    "Order",
    "Orders/{id}",
    new { action = "Show", controller = "Orders", id="" }
);

context.MapRoute(
    "InsertOrder",
    "Orders",
    new { action = "Create", controller = "Orders" }
);

context.MapRoute(
    "UpdateOrder",
    "Orders/{orderID}",
    new { action = "Update", controller = "Orders", orderID = "" }
);

我正在尝试通过 JQuery 创建和更新。当我使用以下内容时:

// Update
var order = getOrder();
$.ajax({
    url: "/orders",
    type: "put",
    data: JSON.stringify(order),
    contentType: "application/json",
    success: function (result) {
        alert(result);
    },
    error: function () {
        alert("There was a problem.");
    }
});


// Create
var order = getOrder();
$.ajax({
    url: "/orders",
    type: "post",
    data: JSON.stringify(order),
    contentType: "application/json",
    success: function (result) {
        alert(result);
    },
    error: function () {
        alert("There was a problem.");
    }
});

我做错了什么?因为它是 404,所以我倾向于认为这是一个不正确的路由。我认为可能存在冲突,但我不知道如何证明或纠正这一点。同时,我不确定我是否在 jQuery 中正确设置了数据属性。感谢您提供的任何帮助。

I have an ASP.NET MVC 3 application. I am trying to implement the routing standard found at http://www.slideshare.net/calamitas/restful-best-practices. I'm using slides 15 and and 17 for reference. I understand that this slide deck is regarding RAILS. However, This syntax seems so much cleaner and more natural. That's why I want to use it.

I have successfully implemented the Index and Show actions in my controller. However, I am having problems getting the Create and Update actions to work. At this time, when I reference either of these, I receive a 404. Currently, my controller looks like this:

public class OrdersController : Controller
{
    // GET: /Orders/
    public ActionResult Index()
    {
        var results = new[] {
            new {id=1, price=1.23, quantity=2}
        };
        return Json(results, JsonRequestBehavior.AllowGet);
    }

    //
    // GET: /Orders/{orderID}
    public ActionResult Show(int id)
    {
        string result = "order:" + id;
        return Json(result, JsonRequestBehavior.AllowGet);
    }

    //
    // POST: /Orders/{order}
    [HttpPost]
    public ActionResult Create(object order)
    {
        var message = "The order was successfully created!";
        return Json(message);
    }

    //
    // PUT: /Orders/{orderID}
    [HttpPut]
    public ActionResult Update(object orderID)
    {
        var message = "The order was successfully updated!";
        return Json(message);
    }
}

When I register my routes, I use the following:

context.MapRoute(
    "OrderList",
    "Orders",
    new { action = "Index", controller="Orders" }
);

context.MapRoute(
    "Order",
    "Orders/{id}",
    new { action = "Show", controller = "Orders", id="" }
);

context.MapRoute(
    "InsertOrder",
    "Orders",
    new { action = "Create", controller = "Orders" }
);

context.MapRoute(
    "UpdateOrder",
    "Orders/{orderID}",
    new { action = "Update", controller = "Orders", orderID = "" }
);

I'm attempting to CREATE and UPDATE via JQuery. When I'm using the following:

// Update
var order = getOrder();
$.ajax({
    url: "/orders",
    type: "put",
    data: JSON.stringify(order),
    contentType: "application/json",
    success: function (result) {
        alert(result);
    },
    error: function () {
        alert("There was a problem.");
    }
});


// Create
var order = getOrder();
$.ajax({
    url: "/orders",
    type: "post",
    data: JSON.stringify(order),
    contentType: "application/json",
    success: function (result) {
        alert(result);
    },
    error: function () {
        alert("There was a problem.");
    }
});

What am I doing wrong? Because its a 404, I tend to believe that it is an incorrect routing. I think there may be a conflict, but I don't know how to prove or correct this. At the same time, I'm not sure that I'm setting the data property correctly in my jQuery. Thank you for any help that can be provided.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

帅气称霸 2024-12-27 10:33:07

您的 URL 缺少创建操作。将 URL 更改为以下内容:

$.ajax({ 
    url: "/orders/create", 
    ....

原因是您的路由永远不会到达为 Orders 定义的第二个路由。所有以 Orders 开头的 url 将转到 Order 控制器和 Index 操作。

context.MapRoute( 
    "OrderList", 
    "Orders", 
    new { action = "Index", controller="Orders" } 
);

编辑:

在这种情况下,您应该使用通用路由:

context.MapRoute( 
    "Order", 
    "Orders/{action}/{id}", 
    new { action = "Index", controller = "Orders", id="" } 
);

如果 URL 是“/Orders”,那么它将转到“Index”,但“/Orders/Create”将转到控制器中的“Create”操作。

Your URL is missing the action for create. Change the URL to the following:

$.ajax({ 
    url: "/orders/create", 
    ....

The reason is that your routing never reach the second one defined for Orders. All url's starting with Orders will go to the Order controller and Index action.

context.MapRoute( 
    "OrderList", 
    "Orders", 
    new { action = "Index", controller="Orders" } 
);

EDIT:

You should use a general routing in this case:

context.MapRoute( 
    "Order", 
    "Orders/{action}/{id}", 
    new { action = "Index", controller = "Orders", id="" } 
);

If the URL is '/Orders' then it will go to 'Index', but '/Orders/Create' will go to the 'Create' action in the controller.

丶视觉 2024-12-27 10:33:07

我认为您只需要下一个 MapRoutes:

routes.MapRoute(
    "OrdersIndex", // Route name
    "{controller}", // URL with parameters
    new {
            controller = "Orders", 
            action = "Index" 
        } // Parameter defaults
);
routes.MapRoute(
    "OrdersCrud", // Route name
    "{controller}/{id}", // URL with parameters
    new { 
            controller = "Orders", 
            action = "Crud"
        } // Parameter defaults
);

然后在您的控制器类中,您将需要类似这样的内容:

public class OrdersController : Controller
{
    // GET: /Orders/
    [HttpGet] //GET is by default
    public ActionResult Index()
    {
        var results = new[] {
            new {id=1, price=1.23, quantity=2}
        };
        return Json(results, JsonRequestBehavior.AllowGet);
    }
    //
    // POST: /Orders/
    [HttpPost]
    public ActionResult Index(object order)
    {   //Create
        var message = "The order was successfully created!";
        return Json(message);
    }

    //
    // GET: /Orders/{orderID} 
    [HttpGet]//GET is by default
    public ActionResult Crud(int id)
    {   //Show
        string result = "order:" + id;
        return Json(result, JsonRequestBehavior.AllowGet);
    }

    //
    // PUT: /Orders/{orderID}
    [HttpPut]
    public ActionResult Crud(object orderWithIDProperty)
    {   //Update
        var message = "The order was successfully updated!";
        return Json(message);
    }

    //
    // DELETE: /Orders/{orderID}
    [HttpDelete]
    public ActionResult Crud(int id)
    {   //Delete
        var message = "The order was successfully deleted!";
        return Json(message);
    }
}

请注意,您不需要显式指定 [HttpGet] 属性,如本 链接

I think you only need the next MapRoutes:

routes.MapRoute(
    "OrdersIndex", // Route name
    "{controller}", // URL with parameters
    new {
            controller = "Orders", 
            action = "Index" 
        } // Parameter defaults
);
routes.MapRoute(
    "OrdersCrud", // Route name
    "{controller}/{id}", // URL with parameters
    new { 
            controller = "Orders", 
            action = "Crud"
        } // Parameter defaults
);

Then in your controller class you would need something like this:

public class OrdersController : Controller
{
    // GET: /Orders/
    [HttpGet] //GET is by default
    public ActionResult Index()
    {
        var results = new[] {
            new {id=1, price=1.23, quantity=2}
        };
        return Json(results, JsonRequestBehavior.AllowGet);
    }
    //
    // POST: /Orders/
    [HttpPost]
    public ActionResult Index(object order)
    {   //Create
        var message = "The order was successfully created!";
        return Json(message);
    }

    //
    // GET: /Orders/{orderID} 
    [HttpGet]//GET is by default
    public ActionResult Crud(int id)
    {   //Show
        string result = "order:" + id;
        return Json(result, JsonRequestBehavior.AllowGet);
    }

    //
    // PUT: /Orders/{orderID}
    [HttpPut]
    public ActionResult Crud(object orderWithIDProperty)
    {   //Update
        var message = "The order was successfully updated!";
        return Json(message);
    }

    //
    // DELETE: /Orders/{orderID}
    [HttpDelete]
    public ActionResult Crud(int id)
    {   //Delete
        var message = "The order was successfully deleted!";
        return Json(message);
    }
}

Note that you don't need to specify explicitly the [HttpGet] attribute as are explained in this link.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文