Soy un novato trabajando con ajax. Tengo un problema al enviar los datos a la publicación ajax. El resultado de console.log(obj.Id) y console.log(oke) es 2. Luego traté de enviarlo a través de datos en ajax, pero terminó en 0 en el controlador.
$(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") } }); }); });Y mi controlador se ve así
[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); }Quiero el valor '2' que pasa a mi controlador, ¿cómo puedo hacer eso? Gracias por tu ayuda.
Cambie la propiedad de datos en la parte 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") } });Una forma alternativa de enviar sus datos a su método de Controller usando Ajax sería envolver sus datos en un objeto JSON y luego enviarlos al servidor para su procesamiento. Luego, el servidor deserializará su objeto JSON y podrá acceder a las propiedades requeridas desde ese proceso:
$(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") } }); }); }); Y su método Controller será:
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); }Si solo necesita una identificación en el parámetro de su método, simplemente cambie los datos en ajax a:
contentType: "application/x-www-form-urlencoded", data: { 'id': oke },id es el nombre del parámetro del método del controlador.