3D-kreativ
3D-kreativ

Reputation: 9301

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"); // ??????
    }

Upvotes: 0

Views: 1293

Answers (2)

MohamedSanaulla
MohamedSanaulla

Reputation: 6242

Along with the correct response status code, you can also pass in your response body error messages from the server may be as JSON string or plain string

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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.

Upvotes: 1

Related Questions