最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ajax call always return success - Stack Overflow

programmeradmin0浏览0评论

I have an ajax call to my controller, which in turn calls a service which returns true or false. I cannot seem to figure out why this always triggers my success function when it returns from controller to view.

Controller

[HttpGet]
public JsonResult TagUnit(int id, string selectedItem)
{
    try
    {
        var result = UnitClient.TagUnit(id, selectedItem);
        if (!result)
        {
            throw new InvalidOperationException();
        }
        return Json(new {success = true}, JsonRequestBehavior.AllowGet);
    }
    catch (Exception e)
    {
        return Json(new {success = false}, JsonRequestBehavior.AllowGet);
    }
}

Cshtml - Javascript - Ajax

 .on("select2-selecting", function (e) {
            var url = '@Url.Content("~/UnitDetails/TagUnit/" + Model.ViewUnitContract.Id)';
            var id = e.val;
            var tagName = e.object.text;
            console.log(id + " : " + tagName);

            $.ajax({
                url: url,
                data: { selectedItem: tagName },
                type: 'GET',
                dataType: 'json',
                success: function () {
                    alert('Success');
                },
                error: function () {
                    alert('Error');
                }
            });
        }).select2('val', ['1', '2']);

What am I missing here?

I have an ajax call to my controller, which in turn calls a service which returns true or false. I cannot seem to figure out why this always triggers my success function when it returns from controller to view.

Controller

[HttpGet]
public JsonResult TagUnit(int id, string selectedItem)
{
    try
    {
        var result = UnitClient.TagUnit(id, selectedItem);
        if (!result)
        {
            throw new InvalidOperationException();
        }
        return Json(new {success = true}, JsonRequestBehavior.AllowGet);
    }
    catch (Exception e)
    {
        return Json(new {success = false}, JsonRequestBehavior.AllowGet);
    }
}

Cshtml - Javascript - Ajax

 .on("select2-selecting", function (e) {
            var url = '@Url.Content("~/UnitDetails/TagUnit/" + Model.ViewUnitContract.Id)';
            var id = e.val;
            var tagName = e.object.text;
            console.log(id + " : " + tagName);

            $.ajax({
                url: url,
                data: { selectedItem: tagName },
                type: 'GET',
                dataType: 'json',
                success: function () {
                    alert('Success');
                },
                error: function () {
                    alert('Error');
                }
            });
        }).select2('val', ['1', '2']);

What am I missing here?

Share Improve this question asked Nov 1, 2013 at 7:58 Nicklas Pouey-WingerNicklas Pouey-Winger 3,0237 gold badges47 silver badges76 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

You should validate server result data in success method.

 $.ajax({
     url: url,
     data: { selectedItem: tagName },
     type: 'GET',
     dataType: 'json',
     success: function (data) {
        if (data != null && data.success) {
            alert('Success');
        } else {
            alert('Error');
        }
     },
     error: function () {
        alert('Error');
     }
 });

Error method calls if on the server occurred 500 error or server is not avaliable, etc.

I think that if you throw an exception, it will still return with a success status code. So what I have done is create an ajax call error handler attribute that can be attached to your MVC methods. It will capture uncaught exceptions, set an error status code and give a generic error message (and also log to Elmah). The attribute is below

public class HandleJsonErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        var serviceException = filterContext.Exception as Exception;

        filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

        filterContext.Result = new JsonResult
        {
            Data = new
            {
                errorMessage = "Generic error message", 
                errorType = 0

            },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };

        var kayttaja = (Kayttaja.TKayttajantiedot)filterContext.HttpContext.Session["userKayttajanTiedot"];
        Global.HandleApplicationError(serviceException, kayttaja);

        filterContext.ExceptionHandled = true;

        // Log to elmah
        //Elmah.ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);
    }
}

Then decorate your action methods that should only be called by Ajax with: [Campus.Attribuutit.HandleJsonError]

The important line for triggering the error handler in the ajax call object is HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError

Don't know if I understand your question properly.

success function in Ajax will execute if the request is successful. And error function will execute if the request fails. You have to check what the server returns inside of the success function.

http://api.jquery./jQuery.ajax/

发布评论

评论列表(0)

  1. 暂无评论