Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Get id after record insert from javascript, client side #4543


User avatar
0
panic created

Hello, Is there a way to get the primary key (id) of the just inserted record, from java-script side? Let's say I have a database table Contact, and below is the java-script code of the modal that i use to create a new contact record. After I click the save button, I use _contactService.createContact to create the new record in the database. Right after this step I need to get the value of the primary key of the new record. Thank you.

_CreateContactModal.js

(function ($) {
    app.modals.CreateContactModal = function () {

        var _modalManager;
        var _contactService = abp.services.app.contact;
        var _$form = null;

        this.init = function (modalManager) {
            _modalManager = modalManager;

            _$form = _modalManager.getModal().find('form');
            _$form.validate();
        };

        this.save = function () {
            if (!_$form.valid()) {
                return;
            }

            var contact = _$form.serializeFormToObject();

            _modalManager.setBusy(true);
            _contactService.createContact(contact).done(function () {
                abp.notify.info(app.localize('SavedSuccessfully'));
                _modalManager.close();
                
                //Here I need to get the id of the newly inserted record

                abp.event.trigger('app.createOrEditUserModalSaved');
            }).always(function () {
                _modalManager.setBusy(false);
            });
        };
    };
})(jQuery);

5 Answer(s)
  • User Avatar
    0
    panic created

    Hello, I have seen that this is possible by using abp.ajax, as you describe at <a class="postlink" href="https://aspnetboilerplate.com/Pages/Documents/Javascript-API/AJAX">https://aspnetboilerplate.com/Pages/Doc ... t-API/AJAX</a> .. however, i am just wondering if there is any other way. Many thanks.

  • User Avatar
    0
    aaron created
    Support Team

    The done handler can have a result parameter: https://aspnetboilerplate.com/Pages/Documents/AspNet-Core#client-proxies

  • User Avatar
    0
    panic created

    Hello Aaron, Thank you very much for your suggestion. It has solved my problem. However, I am facing a next problem: As you can see from above image, the id returned after insert is not the real one. I tried using a synchronous call to insert record but without any success as i get same result. Any suggestions on how to get the real id (primary key) right after inserting a record using a repository insert or insertasync? Many thanks!

  • User Avatar
    0
    panic created

    Oops! Only now I have seen it:<ins>_contactRepository.InsertAndGetIdAsync</ins> Thanks again. Have a good day!

  • User Avatar
    0
    aaron created
    Support Team

    That's great :)