简体   繁体   中英

Firing a server-side method via PageMethod

I wrote a JavaScript function that fires when the user clicks OK in a RadConfirm dialog. This is supposed to trigger a JavaScript callback to the server to delete a record from the database. This may not be the best architecture (I can think of other ways to accomplish my goals) but I'm trying to struggle through this as a learning exercise. Below is the code I've written thus far. I think I've gotten most of it correct.

This Javascript function:

        function confirmCallBackFn(arg) {

        if (arg == true) {
            PageMethods.RemovePackagePageMethod();
        }
        else {
        }
    }

Should invoke the following WebMethod on the server:

    [WebMethod()]
public static void RemovePackagePageMethod(object sender, EventArgs e)
{
    Inventory inv = new Inventory();
    inv.RemovePackage();

}

Which in turn should execute the following method:

    private void RemovePackage()
{
    SBMData2.SBMDataContext db = new SBMData2.SBMDataContext();

    var boxes = from p in db.Packages
                where p.PackageID == Convert.ToInt32(RadGrid1.SelectedValues["PackageID"].ToString())
                select p;

    foreach (var box in boxes)
    {
        db.Packages.DeleteOnSubmit(box);
    }

    try
    {
        db.SubmitChanges();
        RadGrid1.Rebind();
    }
    catch (Exception ex)
    {
        RadWindowManager1.RadAlert("System error deleting package", 200, 200, "exception", null);

    }

}

Everything looks good to me and seems to be consistent with the posts I've read on this site and others about using PageMethod to fire code on the server. However, it's failing to execute the deletion in the final method (which I've tested in isolation). Can someone spot where I went wrong?

You are trying to use the RadGrid1 control in the RemovePackage method, but you are calling the method from a web method, so there is no instance of the Page class, and thus there is no RadGrid1 control.

You would have to send the id of the record that you want to delete from the client code to the web method, and from there along to the RemovePackage method.

Also, you can't rebind the RadGrid1 control to make the changes appear in the page. The web method call is not a page request, so there is no page response that can contain the updated grid. You would have to update the grid in the client code.

尝试将RemovePackage方法设为公开(朋友也可以使用)而不是私有,然后尝试。

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