2

I am returning error message using ajax. the return object like below

{"readyState":4,"responseText":"{\"Message\":\"The request is invalid.\",\"ModelState\":{\"\":[\"Email 'dsfasdf' is invalid.\"]}}","responseJSON":{"Message":"The request is invalid.","ModelState":{"":["Email 'dsfasdf' is invalid."]}},"status":400,"statusText":"Bad Request"}

I want to know whether (showError.responseText).ModelState[""] is exist or not

I tried both following code. But doesn't work

if ((showError.responseText).ModelState[""]) {
            console.log('Key is exist in Object!');
}
if ((showError).hasOwnProperty("ModelState[0]")) {
    console.log('Key is exist in Object!');
}

1 Answer 1

3

The value you're returning contains nested JSON. jQuery will deserialise the parent object for you (assuming the MIME types of the response are configured correctly) however you will need to manually deserialise repsonseText before you can work with it. Try this:

var response = {
  "readyState": 4,
  "responseText": "{\"Message\":\"The request is invalid.\",\"ModelState\":{\"\":[\"Email 'dsfasdf' is invalid.\"]}}",
  "responseJSON": {
    "Message": "The request is invalid.",
    "ModelState": {
      "": ["Email 'dsfasdf' is invalid."]
    }
  },
  "status": 400,
  "statusText": "Bad Request"
}

// in your AJAX handler function:
var rt = JSON.parse(response.responseText);
if (rt.ModelState)
  console.log(rt.ModelState);

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

2 Comments

thanx bro. it works. I will accept answer after 5 min
No problem glad to help

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.