0

I want to return a list of validation errors from my mvc app to the client side to I can take use of the jquery validation showErrors which takes an object

I can get a list of fields and the the erorr(s) that apply to them in any way that is best suited.

I have tried a few formats already, dictionary and none of these serialise to the correct structure as required by the validation library.

ie.

{"fieldname":"some error for fieldname", "fieldname2": "some error for fieldname2"}

All of my examples seem to serialise into something along the lines of

{"Key": "fieldname", "Value" : "some error for fieldname"}

What is the best way to return my data and how can I get it serialised in the correct way that I need?

1 Answer 1

1

I suggest you use Json.NET (it is default JSON serializer for ASP.NET MVC 4 as well) and its JsonWriter:

StringWriter errorsStringWriter = new StringWriter();
JsonWriter errorsJsonWriter = new JsonWriter(jsonStringWriter);
errorsJsonWriter.WriteStartObject();
errorsJsonWriter.WritePropertyName("fieldname"); 
errorsJsonWriter.WriteValue("some error for fieldname");
errorsJsonWriter.WritePropertyName("fieldname2"); 
errorsJsonWriter.WriteValue("some error for fieldname2");
...
errorsJsonWriter.WriteEndObject();
errorsJsonWriter.Flush();

You can return JSON generated this way with ContentResult:

return Content(errorsStringWriter.GetStringBuilder().ToString(), "application/json");

UPDATE

Json.NET also supports dynamic JSON through JObject. In that case your code can look like this:

var jsonObject = new JObject();
jsonObject.Add("fieldname", "some error for fieldname");
jsonObject.Add("fieldname2", "some error for fieldname2");
...

Creating ContentResult in this case can look like this:

    return Content(jsonObject.ToString(Newtonsoft.Json.Formatting.None), "application/json");
Sign up to request clarification or add additional context in comments.

8 Comments

this looks very promising will have to try it out
hmm using the json object just returns [[]]
@DanielPowell You mean the return Json(jsonObject); approach?
@DanielPowell I can't retest it until later today, at this point I can only suggest catsing to dynamic before adding objects to JArray: jsonArray.Add(json as dynamic);. Please check that and let me know if this helps.
|

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.