從給定的第二個URL(這是行不通的)我假設你想用HttpGet
方法使用jQuery AJAX。
http://localhost:123/{controller}/{action}/{id}
這id
視爲UrlParameter
:URL模式與這個路徑相符。
因此就需要使用操作參數&數據表示URL的參數值,如下例所示:
控制器
[HttpGet]
public ActionResult EditRecord(int id)
{
// other stuff
}
視圖(JS)
$.ajax({
url: "/Record/EditRecord",
type: "GET",
dataType: 'json', // response type
contentType: 'application/x-www-form-urlencoded; charset=utf-8', // header content type
data: { id: 1 },
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
替代地直接使用URL參數適用於GET方法而不指定data
內容:
視圖(JS)
$.ajax({
url: "Record/EditRecord/1",
type: "GET",
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
NB:使用jQuery.get
簡化版本:
$.get("/Record/EditRecord/1", function (result) {
Function(result);
}, "json").error(function (message) { // throw error
});
PS:這是HTTP的示例POST請求,如果你正在尋找適當的POST方法與AJAX。
控制器
[HttpPost]
public ActionResult EditRecord(Record rec)
{
// other stuff
}
視圖(JS)
$.ajax({
url: "/Record/EditRecord",
type: "POST",
dataType: 'json', // response type
contentType: 'application/json; charset=utf-8', // header content type
data: JSON.stringify({ rec: { id: 1, name: 'XXXX', ... }}),
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
參考:
Do GET, POST, PUT, DELETE in ASP.NET MVC with jQuery AJAX
兩者的URL相同。什麼是你得到的錯誤 –
對不起,我已經編輯了第二個網址。謝謝。 – MCarmona
'http:// localhost:123/Record/EditRecord/1' =>此請求是否轉到GET方法?我知道如何使用'$ .ajax'來使用各種HTTP方法,但我需要確定你想要使用什麼方法。 –