vote up 2 vote down
star
1

I'm passing json back up from my view to my controller actions to perform operations. To convert the json being sent in, to a POCO I'm using this Action Filter:

public class ObjectFilter : ActionFilterAttribute {
public Type RootType { get; set; }

public override void OnActionExecuting(ActionExecutingContext filterContext) {
IList<ErrorInfo> errors = new List<ErrorInfo>();
try {
    object o = new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
    filterContext.ActionParameters["postdata"] = o;
    }
catch (SerializationException ex) {
    errors.Add(new ErrorInfo(null, ex.Message));
}
finally {
    filterContext.ActionParameters["errors"] = errors.AsEnumerable();
}

}

It's using the DataContractJsonSerializer to map the JSON, over to my object. My Action is then decorated like so:

[ObjectFilter(RootType = typeof(MyObject))]
public JsonResult updateproduct(MyObject postdata, IEnumerable<ErrorInfo> errors) {
    // check if errors has any in the collection!
}

So to surmise, what is going on here, if there is a problem serializing the JSON to the type of object (if a string cannot be parsed as a decimal type or similar for eg), it adds the error to a collection and then passes that error up to the view. It can then check if this collection has an errors and report back to the client.

The issue is that I cannot seem to find out which field has caused the problem. Ideally I'd like to pass back to the view and say "THIS FIELD" had a problem. The SerializationException class does not seem to offer this sort of flexibility.

How would the collective SO hivemind consider tackling this problem?

flag

1 Answer

vote up 1 vote down

I would just do an ajax form post. It's much easier.

http://plugins.jquery.com/project/form

http://malsup.com/jquery/form/

link|flag
This is happening via an ajax form post already. – DaRKoN_ Mar 24 at 4:16
Then you shouldn't need to change the post data to JSON. Just leave the post data in the body of the http request. – Jonathan Parker Mar 24 at 4:52
Unfortunately it's not as straight forward as that. – DaRKoN_ Mar 24 at 10:23
Huh, I thought that ajax could simulate a normal browser post. – Jonathan Parker Mar 24 at 22:18
Sorry I should clarify, it's not a form post. I'm manipulating the data on the client side before serializing and firing off to the server. It's not simple input fields in a form tag. – DaRKoN_ Mar 30 at 5:29

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.