我是一個使用 ajax 的新手。我在將資料發送到 ajax 帖子時遇到問題。console.log(obj.Id)and的輸出console.log(oke)是 2。然后我嘗試通過 ajax 中的資料發送它,但它最終在控制器中為 0。
$(function () {
$("body").on('click', '#btnEdit', function () {
alert("clicked ok");
$("#addRowModal").modal("hide");
var obj = {};
obj.Id = $(this).attr('data-id');
oke = $(this).data("id");
console.log(obj.Id)
console.log(oke)
$.ajax({
url: '@Url.Action("Details", "InvoicePPh")',
data: oke,
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
});
});
我的控制器看起來像這樣
[HttpPost]
public JsonResult Details(int id)
{
var obj = dbContext.invoicePPhs.FirstOrDefault(s => s.Id == id);
InvoicePPh pph = new InvoicePPh();
pph2326.TaxForm = obj.TaxForm;
return Json(pph);
}
我想要傳遞給我的控制器的“2”值,我該怎么做?謝謝您的幫助。
uj5u.com熱心網友回復:
請更改 ajax 部分中的資料屬性。
$.ajax({
url: '@Url.Action("Details", "InvoicePPh")',
data: { id: oke },
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
uj5u.com熱心網友回復:
發送您的Controller方法使用的資料的另一種方法是將您的資料Ajax包裝在一個JSON物件中,然后將其發送到服務器進行處理。然后服務器將反序列化您的JSON物件,您可以從該程序訪問所需的屬性:
$(function () {
$("body").on('click', '#btnEdit', function () {
alert("clicked ok");
$("#addRowModal").modal("hide");
var obj = {};
obj.Id = $(this).attr('data-id');
oke = $(this).data("id");
console.log(obj.Id)
console.log(oke)
var json = {
oke: oke
};
$.ajax({
url: '@Url.Action("Details", "InvoicePPh")',
data: {'json': JSON.stringify(json)},
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
});
});
你的Controller方法將是:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult Details(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var id= Convert.Int32(jsondata["id"]);
var obj = dbContext.invoicePPhs.FirstOrDefault(s => s.Id == id);
InvoicePPh pph = new InvoicePPh();
pph2326.TaxForm = obj.TaxForm;
return Json(pph);
}
uj5u.com熱心網友回復:
如果您只需要方法引數中的 id,只需將 ajax 中的資料更改為:
data: {'id': oke},
id 是控制器方法中的引數名稱。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/424354.html
標籤:javascript C# jQuery 。网 阿贾克斯
