ASP.net MVC 3 - Retrieving Published JSON Data in OnActionExecuting

I send data to actin using the $ .ajax method in jquery, specifying the data to be published using the data field in order to pass JSON string values.

They are sent to the action OK, but I cannot get them in the OnActionExecuting action filter (they are not included in the Forms or Params collections). Is there a way to get them, and if not, can you tell me why not?

+6
json asp.net-mvc asp.net-mvc-3
source share
2 answers

If your action takes a model:

[HttpPost] public ActionResult About(SomeViewModel model) { return Json(model); } 

you could directly use this parameter value because JsonValueProviderFactory already parsed it:

 public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); SomeViewModel model = filterContext.ActionParameters["model"] as SomeViewModel; } 

If there is no model (why not?), You could read JSON from the request stream:

 public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); filterContext.HttpContext.Request.InputStream.Position = 0; using (var reader = new StreamReader(filterContext.HttpContext.Request.InputStream)) { string json = reader.ReadToEnd(); } } 
+11
source share
 protected override void OnActionExecuting(ActionExecutingContext ctx) { //All my viewDto end with "viewDto" so following command is used to find them KeyValuePair<string, object> dto = ctx.ActionParameters.FirstOrDefault(item => item.Key.ToLower().EndsWith("viewdto") ); string postedData; if (dto.Key != null) { object viewData = dto.Value; if (dto.Key.ToLower() == "viewdto") { var stdStoryViewDto = dto.Value as StandardStoryViewDto; //removing unnecessary stuff stdStoryViewDto.Industries.Clear(); stdStoryViewDto.TimeZones.Clear(); viewData = stdStoryViewDto; } postedData = JsonConvert.SerializeObject(viewData); } else { postedData = string.Join(",", Array.ConvertAll(ctx.ActionParameters.Keys.ToArray(), key => key + "=" + ctx.ActionParameters[key]) ); } } 

postedData variable contains JSON data that was sent to the action

0
source share

All Articles