tirsdag den 24. februar 2015

Simple JavaScript callback to asp.net page server method (webservice) - part 2

Simple JavaScript callback to asp.net page server method (webservice)
- easy as client JavaScript method (except call should be asyncrone - se later)
- manage type as JavaScript (don't think of converting to json or xml)

example: JavaScriptValideringSolution_20140331.zip
Another example with javascript calling server with PageMethod for data:

If you want to make easy acces to methods on server from javascript in ASP.NET environment, you just can use a ASPX Webform for hosting af service on the page.
You just need to place a ScriptManager to control access in a ASPX form objet - both with runat sever properties. Rest og the file could be pure Html and javascript.
Remember to eable page methods.

<form id="form1" runat="server">
          <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="True"
                    EnablePartialRendering="true" runat="server"/>

Place the server method on the codebehind c# file with atribute for method like this
In this example it just call another (wcf soap) service to do the job.
In the ASPX page C# page

        public static PostWcfService.PostdistriktDTO[]  GetAllPost(int fromPost, int toPost)
            PostWcfService.PostWcfServiceClient service =
                new PostWcfService.PostWcfServiceClient();
            return service.GetAllePostdistrikterFraTil__PostnrOrder(fromPost, toPost);

In the JavaScript the method is called like this

    PageMethods.GetAllPost(5000, 5200, onSucessGetAllPost, onerrorGetAllPost);

First the parameter to the webmethod followed by at callback method to pass the result and last a callback method i the page method fails.

function onSucessGetAllPost(result)
       // result is an Javascript Array object containing Postdistrict objects
       // and is ready to use -  fx running through by for-loop and displayd in UI
function onerrorGetAllPost(result) {
      // to do for errorhandling

Normally you have a problem calling webmethod on another site,
With this solution we solved the problem with the page method. The page method will act like a proxy/broker for the external service.

You can find a soluton with the example here - also getting data with WebClient for JSON, XML, HTML and TEXT...

An a expanded example with som coverting text from WebClient in JSON, XML and HTML to javascript objects.

Ingen kommentarer:

Send en kommentar