2

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?

2 Answers 2

1

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

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

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

Sign up to request clarification or add additional context in comments.

4 Comments

Then you shouldn't need to change the post data to JSON. Just leave the post data in the body of the http request.
Unfortunately it's not as straight forward as that.
Huh, I thought that ajax could simulate a normal browser post.
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.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.