开发者

ASP.net MVC 3 - Getting posted JSON data in OnActionExecuting

Im posting data to an act开发者_开发问答in using the $.ajax method in jquery, specifying the data to be posted using the data field to pass the JSON stringified values.

These are posted to the action OK but I cant get them in an OnActionExecuting action filter (they're not part of the Forms or Params collections). Is there any way to get them and if not, could you tell share why not?


If your action takes a model:

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

you could directly this parameter value because the JsonValueProviderFactory would have parsed it already:

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

If there is no model (why wouldn't there be?) you could read the 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();
    }
}


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 data in JSON format that was sent to action

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜