現前臺有以下格式的數據須要傳遞到後臺的controller,ajax
1 public class UpdatePara 2 { 3 public int RoleID { get; set; } 4 public List<int> FunctionIDs { get; set; } 5 }
若是按照常規方式傳遞,後臺的controller代碼應該是下面這樣的json
1 public JsonResult Update(UpdatePara para) 2 { 3 var flag = BLLRolePermission.Update(para.RoleID, para.FunctionIDs); 4 return Json(new { success = flag }); 5 }
可是因爲這裏的FunctionIDs是個數組,若是按照上面這種方式接收參數,咱們會發現para.FunctionIDs是null數組
爲了正確獲取參數值,咱們須要自定義個過濾器,代碼以下:ide
1 public class JsonFilter : ActionFilterAttribute 2 { 3 public string ParamName { get; set; } 4 public Type JsonDataType { get; set; } 5 6 public override void OnActionExecuting(ActionExecutingContext filterContext) 7 { 8 string inputContent; 9 var jss = new JavaScriptSerializer(); 10 11 using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream)) 12 { 13 inputContent = sr.ReadToEnd(); 14 } 15 16 var result = jss.Deserialize(inputContent, JsonDataType); 17 18 filterContext.ActionParameters[ParamName] = result; 19 } 20 }
而後,對應的Action方法應該加上過濾器標記spa
1 [JsonFilter(ParamName = "para", JsonDataType = typeof(UpdatePara))] 2 public JsonResult Update(UpdatePara para) 3 { 4 var flag = BLLRolePermission.Update(para.RoleID, para.FunctionIDs); 5 6 return Json(new { success = flag }); 7 }
同時要注意下前臺ajax傳參的時候,json對象要序列化下code
1 JSON.stringify({ 2 roleID: $('#roleID').val(), 3 functionIDs: functionIDs 4 });
That's all.對象