views:

949

answers:

3

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?

+1  A: 

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

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

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

Jonathan Parker
This is happening via an ajax form post already.
DaRKoN_
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
Unfortunately it's not as straight forward as that.
DaRKoN_
Huh, I thought that ajax could simulate a normal browser post.
Jonathan Parker
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_
A: 

Anybody come up with anything?... Very few resources on the web too about this, what a sad situation :(.

David
+1  A: 

How about this: Json.Net It reads a JSON string and then Deserialises it to the given POCO object.

string jsonResult = GetJsonStringFromSomeService();
MyPocoObject myobject = JsonConvert.DeserializeObject<MyPocoObject>(jsonResult);
Console.Write("Damn that is easy");

But for the determing where errors occur, I am not too sure.

burnt_hand