简体   繁体   中英

Javascript calling webservice and ASP.Net Sequence

I`m using Javascript function that uses a web service and after finishing it i have to update a Grid Datasource

To accomplish this task i called the javascript function via RegisterClientScriptBlock then call the UpdateGridDataSource method

But While Debugging i found that it calls the UpdateGridDataSource method first .. Then Call the method in the WebService!

ASP.Net Code

System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "delete", "DrawPOI();", true);

UpdateDataSource(); 

JavaScriptCode

function DeletePOI(arg) {
      //Some Code  
        $.ajax({
            url: "JSBLL.asmx/DeletePOI",
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: "{id:'" + arg + "'}",
            success: function (msg) {
                alert(msg.d);
            },
            error: function (e) {
                alert('Error');
            }
        }); //some code
        return false;
    }

WebService :

[WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string DeletePOI(string ID)
        try
            {
                if (id == "")
                    throw new Exception();

                long ID = Convert.ToInt64(id);
                using (GuardEntities database = new GuardEntities())
                {
                    var poi = database.POIs.Where(x => x.ID == ID).FirstOrDefault();

                    database.POIs.DeleteObject(poi);
                    database.SaveChanges();
                }

                return "POI Deleted Successfully";
            }
            catch
            {
                return "Error Occured";
            }
}

The Problem is that UpdateDataSource() is called before DeletePOI(string ID)

Javascript code registered with RegisterClientScriptBlock() runs on the client in the browser. ASP.NET code runs on the server.

When it gets to the line:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "delete", "DrawPOI();", true);

It says, when the page loads on the client, call DrawPOI() . It then immediately runs the next line of code:

UpdateDataSource(); 

When it's done with all the ASP.NET code, it then sends your page to the client. Basically, what you are trying to do will not work. You can't call client-side Javascript in the middle of your server-side ASP.NET code and wait for it to return.

What you can do is call the web service directly from your server-side code.

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