Medoo
Medoo

Reputation: 23

how to distinguish between JSON messages passed to view?

my question is : how to distinguish between JSON messages passed to view? OR
how to distinguish between JSON success and error messages?

I have the following ajax post and a method to return JSON. but whatever message sent to the view I get just message by the first function of "success" I don't get fail message even if code-behind failed!!

AJAX POST

        $('#CreateLesson').on('submit', function (e) {

            e.preventDefault();
            var lesson = $(this).serialize();
            var Url = $(this).attr('action');

            $.post(Url, lesson,
                function (d) { alert(JSON.stringify(d)); })
                .fail(function (response) { alert("error !!"); });

        });

Method return JSON

    [HttpPost]
    public JsonResult Create(Lesson lesson)
    {
        if (ModelState.IsValid)
        {
            _context.Add(lesson);
            _context.SaveChanges();
            return Json(lesson);
        }
        return Json("There is something went wrong!! The lesson hasn't been add");
    }

Again, I always return method results via first function. How did I know? I never get the second function result Alert("error !!")

what should I do to return JSON to the second function if the ModelState.IsValid = false ?

Upvotes: 0

Views: 31

Answers (1)

Rena
Rena

Reputation: 36715

The error function is executed if the server responds with a HTTP error. Although your code makes error but you return Json,this would get Http Code 200 which is a successful response.Only if you get a http error code,the ajax error function could be triggered.

Reference:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

You could throw an exception to make a Http 500 error or return BadRequest to make a Http 400 error.Change your code like below:

public IActionResult Create(Lesson lesson)
{
    if (ModelState.IsValid)
    {
        return Json(lesson);         
    }
    //throw new Exception("There is something went wrong!! The lesson hasn't been add");
    return BadRequest("There is something went wrong!! The lesson hasn't been add");
}

Result for return json:

enter image description here

Result for Http Error: enter image description here

Upvotes: 0

Related Questions