imak
imak

Reputation: 6699

detect if ajax call succeeded or not

Here is my ajax call

$.ajax({
            type: "POST",
            url: "MyMethod",
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({  Param1: 'value1', Param2: 'value2'}),
            success: function (msg) { location.href = '@Url.Action("MyActionMethod", "MyController")'; },
            error: function (msg) { alert(msg); }
        });

This is my model

public class MyModel
{
    public string Param1 { get; set; }
    public string Param2 { get; set; }
}

MyMethod implementation is as follows

public bool MyMethod(MyModel model)
{

    if (!ValidateModel(model) )
    {
        // I want to error a descriptive error  
        return false;
    }

    // Some other processing
    return true;
}

Problem is that I don't know how does it determine if call is a success or failure. Returning ture/false does not seem to help as code always go in the success code path (that is it redirects to MyController.MyActionMethod). Any ideas what i am doing wrong

Upvotes: 1

Views: 312

Answers (2)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107536

This is usually what I do:

public JsonResult MyMethod(MyModel model)
{
    var success = true;
    var result = string.Empty;

    if (!ValidateModel(model) )
    {
        // I want to error a descriptive error  
        success = false;
        result = "Invalid model";
    }

    // Some other processing
    return Json(new { success = success, error = result }, 
        JsonRequestBehavior.Allow);
}

Note the change in the return method from bool to JsonResult. And then in your JavaScript you could test the properties coming through on the JSON object:

...
success: function (msg) { 
   if (msg.success) {
       location.href = '@Url.Action("MyActionMethod", "MyController")'; 
   } else {
       alert(msg.error);
   }
},
...

Upvotes: 3

SLaks
SLaks

Reputation: 887459

In order to trigger jQuery's error handler, you need to return an HTTP error.
To do that, set Response.StatusCode to 400 (Bad Request).

Alternatively, you can return JSON from the action and read properties object in the success handler to get an error message or a URL.

Upvotes: 1

Related Questions