This is a migrated thread and some comments may be shown as answers.

Canceling OnSave & doing it all in javascript

6 Answers 149 Views
Grid
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Kevin
Top achievements
Rank 1
Kevin asked on 20 Sep 2011, 09:28 PM
So I have this situation where I need user feedback when the user clicks the update button after a save or insert.  
http://www.telerik.com/community/forums/aspnet-mvc/grid/asking-for-user-input-in-the-controller.aspx

This forces me to use "e.preventDefault();" in the OnSave client event to cancel the OnSave server-side controller action.  Fine, so I can do all the updating on client-side the with ajax calls, etc.  HOWEVER: When I am done, how to I change the edited row back to it's display state, preserving any changes that were made?

Remember: Since I am using Ajax, I have to use e.preventDefault() because the success call back is asynchronous, otherwise I would just let the grid itself change the updated row back to a display state.

Steve

6 Answers, 1 is accepted

Sort by
0
Kevin
Top achievements
Rank 1
answered on 21 Sep 2011, 08:37 AM
Also, do I have to do anything special if this is a child grid?  Child grids are tricky because the primary key of the parent is appended to the name of the child grid.

Steve
0
John DeVight
Top achievements
Rank 1
answered on 26 Sep 2011, 05:18 PM
Hey Steve,

If I understand your question correctly, you want to edit a row.  When  the user clicks the update button, you want to get additional input.  Based on the additional input, you may or may not want to post the update to the server.  If you do not post the update to the server, you still want to preserve the values entered.

I've put together a sample application that does this.  I needed to "override" the grid.updateRow function with my own updateRow function.  However, I only wanted to apply this to a specific instance of a grid (I have an article that talks about doing this: Extending an Object Function with jQuery ).  Anyway, to do this, I created an extension function called overrideUpdateRow.  I extend the grid with the overrideUpdateRow function in the grid.onLoad event.  I call overrideUpdateRow for the specific grid.  The overrideUpdateRow function takes a function pointer as a parameter.  This function pointer gets called to determine whether to perform the update to the server or just update the "client data".  The function pointer is passed all the data that is about to be updated.  The function pointer returns true to continue with the update to the sever or false to not update to the server and only update the "client data".

Here is the declaration for the grid:

@{
    Html.Telerik().Grid<TelerikMvcRazorApp.Models.Person>()
        .Name("PersonGrid")
        .DataKeys(keys => keys.Add(m => m.Id))
        .DataBinding(dataBinding => dataBinding.Ajax()
            .Select("SelectPeople", "Home")
            .Update("UpdatePerson", "Home")
        )
        .Columns(columns =>
        {
            columns.Bound(m => m.FirstName);
            columns.Bound(m => m.LastName);
            columns.Command(commands =>
            {
                commands.Edit();
            }).Width(100);
        })
        .ClientEvents(events => events
            .OnLoad("PersonGrid_onLoad")
        )
        .Filterable(filtering => filtering.Enabled(true))
        .Sortable(sorting => sorting.Enabled(true))
        .Render();
}

Here is the PersonGrid_onLoad function that creates the extension function and adds it to the PersonGrid:

PersonGrid_onLoad=function (e) {
    var gridExtensions={
        overrideUpdateRow: function (fp) {
            this.overrideUpdateRowFunctionPointer=fp;
            this["updateRowBase"]=this.updateRow;
            this.updateRow=function (m) {
                if(this.validate()) {
                    function d(n) {
                        var k=/^\/Date\((.*?)\)\/$/;
                        var o,m,p;
                        for(o in n) {
                            m=n[o];
                            if(typeof m==="string") {
                                p=k.exec(m);
                                if(p) {
                                    n[o]=new Date(parseInt(p[1]))
                                }
                            }
                            else {
                                if(jQuery.isPlainObject(m)) {
                                    d(m)
                                }
                            }
                        }
                    };
                    var n=this.dataItem(m.data("tr")||m);
                    var o=this.extractValues(m,(this.editing.mode!="InCell"||!this.ws));
                    //if(c.trigger(this.element,"save",{
                    if(jQuery.telerik.trigger(this.element,"save",{
                        mode: "edit",
                        dataItem: n,
                        values: o,
                        form: this.form()[0]
                    })) {
                        return
                    }
                    if(this.editing.mode=="InCell") {
                        o=jQuery.extend(n,o);
                    }
                    o=jQuery.extend(n,o);
                    d(o);
 
                    //this.sendValues(o,"updateUrl")
                    var data=this._convert(o);
                    if(this.overrideUpdateRowFunctionPointer(data)) {
                        this.sendValues(data,"updateUrl");
                    }
                    else {
                        var row=$($.find('tr.t-grid-edit-row'));
                        this.rowEditor.cancel(row,data);
                        $.telerik.trigger(this.element,"rowDataBound",{
                            row: row[0],
                            dataItem: data
                        });
                    }
                }
            }
        }
    };
    $.extend(true,$.telerik.grid.prototype,gridExtensions);
    $('#PersonGrid').data('tGrid').overrideUpdateRow(PersonGrid_overrideOnSave);
}

Here is the PersonGrid_overrideOnSave function that gets called when the update button is clicked:

PersonGrid_overrideOnSave=function (data) {
    // console.log(data);
    return confirm("Are you sure you want to save?");
}

I'll roll this capability into my telerik.extensions.js this week after I've made sure this works for you!

Attached is a sample application.

Regards,

John DeVight
0
Accepted
John DeVight
Top achievements
Rank 1
answered on 27 Sep 2011, 02:10 AM
Hi Steve,

Thanks for your emails clarifying what the issue is.  Here is the updated PersonGrid_overrideOnSave function that uses the jQuery.ajax function with async set to false to wait for the response before continuing on:

PersonGrid_overrideOnSave=function (data) {
    $.ajax({
        url: '/Home/ValidatePerson',
        type: 'POST',
        data: data,
        async: false,
        success: function (response) {
            if(response==false) {
                alert("The last name must be Smith to save back to the server.  "+
                      "The values you entered will be saved on the client.  Please "+
                      "click update again and change the last name to Smith");
            }
            return response;
        }
    });
}

Here is the ValidatePerson method in the HomeController:

public JsonResult ValidatePerson(Person person)
{
    return Json((person.LastName == "Smith"), JsonRequestBehavior.AllowGet);
}

Attached is the updated sample application.  Hope this helps.

Regards,

John DeVight
0
Kevin
Top achievements
Rank 1
answered on 27 Sep 2011, 04:41 AM
Wow, worked like a charm.  I'm not sure even how it works.  I didn't even have to return anything inside the success callback.  My update controller method defined in the grid is never called.  But that's OK, I'm doing everything I want in my success callback and it's probably not being called because I am not returning true.  I have to double check a couple things tomorrow morning, but all in all it looks like it works.

Thanks once a again, John!  You are a champ and an MVP!!

Steve
0
John DeVight
Top achievements
Rank 1
answered on 27 Sep 2011, 01:52 PM
Great to hear that it worked for you! =)

Regards,

John DeVight
0
Tomas
Top achievements
Rank 1
answered on 06 Oct 2011, 07:15 PM
Hi, geat post. But it dont work if you define PopUp edit.
Do you know why?

Other question its,
I have a grid of users, inside my edit popup form i have define a grid with checkbox selection , do you know how i can pass the selected checkbox to my controller.

Tags
Grid
Asked by
Kevin
Top achievements
Rank 1
Answers by
Kevin
Top achievements
Rank 1
John DeVight
Top achievements
Rank 1
Tomas
Top achievements
Rank 1
Share this question
or