简体   繁体   中英

Pass message from Controller to AJAX script in View

I'm using jQuery and AJAX in the View to send some data to the Controller that writes it to the database. On success I show a div tag with a green background with "OK" text. But what if I do a check first in the Controller if the data already exist in the database, then I would like to alert the user that the data could not be added. Is there a way to pass some kind of message back to the AJAX script?

I guess the success option is just a confirm of contact with the Controller and not a real confirm that everything is OK and the data has been added to the database!?

What action in the Controller would cause the error function in the AJAX code to run?

Finally I just wonder what kind of return I should use since I'm actually not returning anything?

My script in the View:

        $.ajax({
        url: "/Orders/AddOrder",
        type: "GET",
        cache: false,
        data: { a: order, b: seller },
        success: function () {
            console.log('AJAX successful');

        // Show confirm message
            $(".messageOk").show();
            $(".messageOk").text("OK").delay(2000).queue(function () {
                location.reload();
            });
        },
        error: function () {
        ????
        },
        complete: function () {
        ????
        }
    });

Controller:

        // Add new Resource
    public ActionResult AddOrder(int a, int b)
    {
        var order = new Order
        {
            OrderNumber = a,
            Seller = b
        };

        db.Orders.Add(order);
        db.SaveChanges();

        //return new EmptyResult();

        return RedirectToAction("Index", "Home"); // ??????
    }

You could return the appropriate HTTP status code from your controller action: 409 Conflict .

if (the resource already exists in db) {
    return new HttpStatusCodeResult(HttpStatusCode.Conflict);
}

which will trigger the error AJAX function in which you could check whether you are in this situation and act accordingly:

error: function(jqXHR) {
    if (jqXHR.status == 409) {
        alert('Sorry but this resource already exists');
    }
}

As you can see this way it's up to the view to decide what error messages to display based on proper HTTP status codes returned from the server. This way you are not cluttering the server with view logic.

除了正确的响应状态代码外,您还可以将响应主体的错误消息从服务器传递为JSON字符串或纯字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM