[英]Why it value does not send in to ajax post?
我是使用 ajax 的新手。我在將數據發送到 ajax 后遇到問題。 console.log(obj.Id)
和console.log(oke)
的output是2。然后我嘗試通過ajax中的數據發送,但在controller中最終為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") } }); }); });
我的 controller 看起來像這樣
[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); }
我想要傳遞到我的 controller 的“2”值,我該怎么做? 謝謝您的幫助。
請更改 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")
}
});
使用Controller
發送數據的另一種方法是將數據包裝在JSON
Ajax
中,然后將其發送到服務器進行處理。 然后服務器將反序列化您的JSON
object 並且您可以從該過程訪問所需的屬性:
$(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",
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);
}
如果您只需要方法參數中的 id,只需將 ajax 中的數據更改為:
contentType: "application/x-www-form-urlencoded",
data: { 'id': oke },
id 是 controller 方法的參數名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.