gpt4 book ai didi

jquery - ASP.NET MVC 3 和静态路由

转载 作者:行者123 更新时间:2023-12-01 00:15:54 25 4
gpt4 key购买 nike

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

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

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 中正确设置了数据属性。感谢您提供的任何帮助。

最佳答案

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

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

原因是您的路由永远不会到达为订单定义的第二个路由。所有以 Orders 开头的 url 将转到 Order Controller 和 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”将转到 Controller 中的“Create”操作。

关于jquery - ASP.NET MVC 3 和静态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8448420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com