問題:在一般處理程序(.ashx)中累加[index='b']的值 難點:前台獲取JSON值后台解析 解決: //#region 把index=b的值存在JSON對象中 function AjaxGetSum() { var arr = []; $("input[index='b']").each(function () { var arrObject = {}; var tempVal = $(this).val(); if (!$.gstr.isEmpty(tempVal)) { //本公司自己封裝的js $.gstr.isEmpty(st) 判斷st是否為空,返回true/false arrObject["inValue"] = tempVal; arr.push(arrObject); } }); var JsonString = JSON.stringify(arr); //轉換成JSON類型的字符串 $.post("HandlerSum.ashx", { jsonVar: JsonString }, function (data) { alert(data); }) } //#endregion
using System;
using System.Collections.Generic; using System.Linq; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Converters; namespace Train_First.Ajax_Rpc { /// <summary> /// HandlerSum 的摘要說明 /// </summary> public class HandlerSum : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string ss = context.Request.Form["jsonVar"]; //獲取前台傳遞過來的授課JSON字符串數組 JArray javascript = (JArray)JsonConvert.DeserializeObject(ss); //反序列化獲取的JSON字符串數組 string StringSum = ""; for (int i = 0; i < javascript.Count; i++) { JObject obj = (JObject)javascript[i]; string outValue = obj["inValue"].ToString(); //將一個個反序列化的JSON字符串數組轉換成對象 StringSum += outValue; } context.Response.Write(StringSum); } public bool IsReusable { get { return false; } } } }