【发布时间】:2011-12-09 16:17:05
【问题描述】:
我有一个 ASP.NET MVC 3 应用程序。我正在尝试实现http://www.slideshare.net/calamitas/restful-best-practices 的路由标准。我使用幻灯片 15 和 17 作为参考。我知道这个幻灯片是关于 RAILS 的。但是,这种语法看起来更干净、更自然。这就是我想使用它的原因。
我已经在我的控制器中成功实现了 Index 和 Show 操作。但是,我无法让 Create 和 Update 操作正常工作。此时,当我引用其中任何一个时,我都会收到 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 中正确设置了 data 属性。感谢您提供的任何帮助。
【问题讨论】:
-
为什么你的两条路线有相同的 url?
标签: jquery asp.net-mvc-3 asp.net-mvc-routing