0

When I am submitting form via Ajax, I have 2 ways of showing the user validation error messages:

1) If everything is ok return Json(new { Status = true }), if there are errors return View(model) in controller. And then on client side something like if (response.Status == undefined) $("#formWrapper).html(response) which will replace form with new one which contains error messages.

2) If everything is ok return Json(new { Status = true }), and if there are errors return Json(new { Status = false, Errors = errorList }) and then on client side go through errorList and append messages to elements.

Which one should I choose?

Note: I know I have client side validation and request wont be submitted at all if there are errors, but there are some things that need to be checked on backend and cant be put in client side validation, so I need mechanism to return info about validation errors from controller.

2
  • Choose the second one all day long :) Maybe also instead of true and false, you can set a value like 1 and -1 Commented Mar 24, 2017 at 10:38
  • 1
    Option 2 will be better performance, and not require the $.validator to be re-parsed Commented Mar 24, 2017 at 10:48

3 Answers 3

1

I would suggest the first one. You tend to avoid more bugs when you completely replace views, data, or just about anything instead of changing it.

The second one is basically changing the state of the view. Changing state is one of the biggest sources of bugs in programming.

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

Comments

1

I would go with option two as you can get more information of the error in the client side (Other then just view) and display the perfect error message. Like user entered wrong or the data caused error or any custom one from the server side as you mentioned error list.

Comments

0

My suggestion is different when you Success return

Json(new { Status = true })

and when catch any error Set Response.StatusCode with some types to handle it in ajax error callback I always do that code below.

Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(result.ErrorMessage);

with this approach you will be seperated the concerns.

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.