Pertama unduh kode JavaScript ini, JSON2.js , yang akan membantu kami membuat serial objek menjadi string.
Dalam contoh saya, saya memposting baris jqGrid melalui Ajax:
var commissions = new Array();
// Do several row data and do some push. In this example is just one push.
var rowData = $(GRID_AGENTS).getRowData(ids[i]);
commissions.push(rowData);
$.ajax({
type: "POST",
traditional: true,
url: '<%= Url.Content("~/") %>' + AREA + CONTROLLER + 'SubmitCommissions',
async: true,
data: JSON.stringify(commissions),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.Result) {
jQuery(GRID_AGENTS).trigger('reloadGrid');
}
else {
jAlert("A problem ocurred during updating", "Commissions Report");
}
}
});
Sekarang di pengontrol:
[HttpPost]
[JsonFilter(Param = "commissions", JsonDataType = typeof(List<CommissionsJs>))]
public ActionResult SubmitCommissions(List<CommissionsJs> commissions)
{
var result = dosomething(commissions);
var jsonData = new
{
Result = true,
Message = "Success"
};
if (result < 1)
{
jsonData = new
{
Result = false,
Message = "Problem"
};
}
return Json(jsonData);
}
Buat Kelas JsonFilter (berkat referensi JSC).
public class JsonFilter : ActionFilterAttribute
{
public string Param { get; set; }
public Type JsonDataType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
{
string inputContent;
using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
{
inputContent = sr.ReadToEnd();
}
var result = JsonConvert.DeserializeObject(inputContent, JsonDataType);
filterContext.ActionParameters[Param] = result;
}
}
}
Buat kelas lain sehingga filter dapat mengurai string JSON ke objek aktual yang dapat dimanipulasi: Kelas comissionsJS ini adalah semua baris jqGrid saya.
public class CommissionsJs
{
public string Amount { get; set; }
public string CheckNumber { get; set; }
public string Contract { get; set; }
public string DatePayed { get; set; }
public string DealerName { get; set; }
public string ID { get; set; }
public string IdAgentPayment { get; set; }
public string Notes { get; set; }
public string PaymentMethodName { get; set; }
public string RowNumber { get; set; }
public string AgentId { get; set; }
}
Saya harap contoh ini membantu mengilustrasikan cara memposting objek yang kompleks.