Solved

a code behind method that can be called from a javascript and return list of strings

Posted on 2010-08-19
37
518 Views
Last Modified: 2012-05-10
I have an aspx page that has a javascript and I wanted to use a code behind method that can accept parametrs and returns list of strings based on some operation to be performed. Here I am more interested to ensure the wiring between the javacript and the code behind method. Moreover I want to use the value returned from the web method in the java script for additional operations . Hence I have to store the value somewhere like in a hidden variable or some other variable. I have tried a webmethod but I am facing the problem of not getting the value returned from the web method outside of the onsuccess call back function . You can see the following code.

SO my question is do I have any other better option. or it that impossible to use the value retured by a web method ouside of the onsuccess call back fucntion? I need a help please





function webMethodCaller( ids){

         PageMethods.FormatName(ids,  onFormatNameSuccess,  onFormatNameFail,     onFormatNameTimeout);        

       

// i want to do something else based on result after this

//if I try to get the value in a hidden filed in here it is empty

}



 function onFormatNameSuccess(response)

{

      

                  

      var res="";

      

      for(var i=0,il=response.length; i<il;i++){

      res+=response[i];

      }

      

// i am trying to store the value in a hidden field for later use

      document.getElementById("HiddenField1").value = res;

//if i try to see the vaue of the hidden fiedl in here it is there but not ouside this fucntion

}



function onFormatNameFail (exception, ctx, methodName) 

{ 

       alert("Method:"+ methodName +"\n"+ 

            exception.get_exceptionType() +"\n"+

            exception._message); 

}

function onFormatNameTimeout () 

{ 

      alert("Timeout"); 

}

















///////////////////////////////////////////////



   <form id="form1" runat="server">

        <asp:HiddenField ID="hdnReturnValue" runat="server" Value="xx" />

        <asp:HiddenField ID="HiddenField1" runat="server" />

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        <input type="hidden" id="hiddnvalue" runat="server" value="" />

        <asp:ScriptManager ID="yourScriptManager" runat="server" EnablePageMethods="true">

        </asp:ScriptManager>

    </form>





the web method is the folloiwng

///////////////////////////////////////



 [WebMethod, ScriptMethod]

        static public List<String> FormatName(string featureIds)

        {

           



            string[] rawdata = featureIds.Split(new char[] { ',' });



            List<String> strings = new List<String>();

            for (int i = 0; i < rawdata.Length; i++)

            {

                strings.Add(rawdata[i]);

            }

            // strings.Add(FirstName);

            // strings.Add(LastName);*/



            //Session["result"] = strings;

            //   hdnReturnValue.value = strings;

          //  HiddenField1.Value = featureIds;

           // hiddnvalue.Value = featureIds;

            return strings;

            // LastName + ", " + FirstName;

        }

Open in new window

0
Comment
Question by:AbebeDemeke
  • 18
  • 17
  • +1
37 Comments
 
LVL 25

Expert Comment

by:Luis Pérez
ID: 33474606
That's very easy using Ajax.

For example, jQuery Ajax:
http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Hope that helps.
0
 
LVL 20

Expert Comment

by:informaniac
ID: 33474640
You can also take a look at ClientCallBack
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33475732
@AbebeDemeke,

type PageMethods in Google and confirm you generaly don't see anything after PageMethods call.

PageMethods do an asynchrone ajax call mean :
1- do the call an continue the execution of the code

and not :
2- do the call, wait for result and execution and continue.

if the first case you can't use result of the pagemethod call immediately because the call just start in parallel
in the second case you are able to use the result because you wait for the end of the call.

@RolandDeschain give you an other link to do a SYNCHRONE ajax call.

0
 

Author Comment

by:AbebeDemeke
ID: 33475820
leakim971: thanks

and it seems that the problem is as you pointed out but do u know how can i do a synchronized ajax call. a simple example would help me a lot
0
 

Author Comment

by:AbebeDemeke
ID: 33475973
leakim971:one question for you can i pass a parameter to the on success call back function so that I can finish everything there?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33476173
>a simple example would help me a lot
@RolandDeschain give you an other link to do a SYNCHRONE ajax call.
You just need to add :

$.ajax({
  async: false,
  type: "POST",

else again : http://kpumuk.info/asp-net/synchronous-page-method-call-in-asp-net-ajax-library/

A fast example
Where PageName.aspx is your page having the webmethod
if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("POST","PageName.aspx/FormatName",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("parameter1=Value1&parameter2=Value2");
xmlhttp.send();
document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;

Open in new window

0
 

Author Comment

by:AbebeDemeke
ID: 33476210
i am not sure where do i put those fragment of codes?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33476288

function webMethodCaller( ids){
     if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     xmlhttp.open("POST","PageName.aspx/FormatName",false);
     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     xmlhttp.send("parameter1=Value1&parameter2=Value2");
     xmlhttp.send();

// i want to do something else based on result after this
//if I try to get the value in a hidden filed in here it is empty
document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;
}

Open in new window

0
 

Author Comment

by:AbebeDemeke
ID: 33476356
thaks but then do I need to change my web method and if then how?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33476390
have a look to the good article propose by @RolandDeschain
0
 

Author Comment

by:AbebeDemeke
ID: 33477108
leakim971: please would you mind to make your answer complete? I appriciate your help so much

I have
function webMethodCaller( ids){
     if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     xmlhttp.open("POST","PageName.aspx/FormatName",false);
     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     xmlhttp.send("parameter1=Value1&parameter2=Value2");
     xmlhttp.send();

// i want to do something else based on result after this
//if I try to get the value in a hidden filed in here it is empty
document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;
}

which means I dont have to call the page method like?

PageMethods.FormatName(ids,onFormatNameSuccess,onFormatNameFail,onFormatNameTimeout);

Moreover where do i put the code fragment

$.ajax({
  async: false,
  type: "POST",




0
 
LVL 82

Expert Comment

by:leakim971
ID: 33477588
>which means I dont have to call the page method like?
>PageMethods.FormatName(ids,onFormatNameSuccess,onFormatNameFail,onFormatNameTimeout);
Yes

>Moreover where do i put the code fragment
>$.ajax({
> async: false,
> type: "POST"
no need too, it's a jquery version

PageMethods : .net Ajax call
$.ajax : jQuery

pure javascript :
function webMethodCaller( ids){
     if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     xmlhttp.open("POST","PageName.aspx/FormatName",false);
     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     xmlhttp.send("parameter1=Value1&parameter2=Value2");
     xmlhttp.send();
     document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;
}

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 33477883
correction you must remove line 6 : xmlhttp.send();

(only one send of course)

and its safe to use encodeURI
function webMethodCaller( ids){
     if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     xmlhttp.open("POST","PageName.aspx/FormatName",false);
     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     xmlhttp.send(encodeURI("featureIds=" + ids));
     document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;
}

Open in new window

0
 

Author Comment

by:AbebeDemeke
ID: 33477952
OK how do i pass my parmeters in this case ids?

is it like  xmlhttp.send("parameter1=ids");

morover since the page method is in the code behind of the page containing the java script will the folloiwng work

xmlhttp.open("POST","FormatName",false); ?

finally do i need to keep my previous web method as it is like :


 [WebMethod, ScriptMethod]
        static public List<String> FormatName(string featureIds)
        {
           
            string[] rawdata = featureIds.Split(new char[] { ',' });

            List<String> strings = new List<String>();
            for (int i = 0; i < rawdata.Length; i++)
            {
                strings.Add(rawdata[i]);
            }
   

       
            return strings;
         
           

        }
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33478173
>OK how do i pass my parmeters in this case ids?
check line 5 : xmlhttp.send(encodeURI("featureIds=" + ids));

>finally do i need to keep my previous web method as it is like :
create a webservice with :


[WebMethod]
public List<String> FormatName(string featureIds)
{
            string[] rawdata = featureIds.Split(new char[] { ',' });

            List<String> strings = new List<String>();
            for (int i = 0; i < rawdata.Length; i++)
            {
                strings.Add(rawdata[i]);
            }
            return strings;
}

Open in new window

0
 

Author Comment

by:AbebeDemeke
ID: 33478567
the xmlhttp.responseText is a long html code.

how can I extract the string list returned by the web method?

if at  all possible?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33478689
>xmlhttp.responseText is a long html code

do you see you data inside ? Perhaps is a error page.
If you saw your data, yes we can!

just post it here, in code snipet, to let we see it
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33478694
and say witch part/string you want to get
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:AbebeDemeke
ID: 33479067
well what i need is the string returned by the webmethod. I dont need the other and I dont really know where it is located in the code. However after taking out the part of the html that contains my conde follwoing is the rest returned as xmlhttp.responoseText

<input type=\"hidden\" name=\"__EVENTTARGET\" id=\"__EVENTTARGET\" value=\"\" />
<input type=\"hidden\" name=\"__EVENTARGUMENT\" id=\"__EVENTARGUMENT\" value=\"\" />
<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"/wEPDwUKLTI0NDQ5NDAwOWRk+xP7p8daFyNLYiR19DwIZihK0J0=\" />
</div>

<script type=\"text/javascript\">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>


<script src=\"/WebResource.axd?d=W8uJCuYzqaZgFZVW92HeEg2&amp;t=633697903278952835\" type=\"text/javascript\"></script>


<script src=\"/ScriptResource.axd?d=CexzdgQeXWxJFoiTDPLHRhHW8BopNhuJXu1PpwHKi4GD0aZYyIkqVAh5sir4Lut4YGcJ2FX1KmHJPLgL5u5YbgAXJy901ffWht5-gi5fFDk1&amp;t=ffffffffdb87df90\" type=\"text/javascript\"></script>
<script src=\"/ScriptResource.axd?d=CexzdgQeXWxJFoiTDPLHRhHW8BopNhuJXu1PpwHKi4GD0aZYyIkqVAh5sir4Lut4AKg24qXhrbuX8JaVACwgKD7J27LMh309rZT-49R29zQ1&amp;t=ffffffffdb87df90\" type=\"text/javascript\"></script>
<script type=\"text/javascript\">
//<![CDATA[
var PageMethods = function() {
PageMethods.initializeBase(this);
this._timeout = 0;
this._userContext = null;
this._succeeded = null;
this._failed = null;
}
PageMethods.prototype = {
_get_path:function() {
 var p = this.get_path();
 if (p) return p;
 else return PageMethods._staticInstance.get_path();},
FormatName:function(featureIds,succeededCallback, failedCallback, userContext) {
return this._invoke(this._get_path(), 'FormatName',false,{featureIds:featureIds},succeededCallback,failedCallback,userContext); }}
PageMethods.registerClass('PageMethods',Sys.Net.WebServiceProxy);
PageMethods._staticInstance = new PageMethods();
PageMethods.set_path = function(value) { PageMethods._staticInstance.set_path(value); }
PageMethods.get_path = function() { return PageMethods._staticInstance.get_path(); }
PageMethods.set_timeout = function(value) { PageMethods._staticInstance.set_timeout(value); }
PageMethods.get_timeout = function() { return PageMethods._staticInstance.get_timeout(); }
PageMethods.set_defaultUserContext = function(value) { PageMethods._staticInstance.set_defaultUserContext(value); }
PageMethods.get_defaultUserContext = function() { return PageMethods._staticInstance.get_defaultUserContext(); }
PageMethods.set_defaultSucceededCallback = function(value) { PageMethods._staticInstance.set_defaultSucceededCallback(value); }
PageMethods.get_defaultSucceededCallback = function() { return PageMethods._staticInstance.get_defaultSucceededCallback(); }
PageMethods.set_defaultFailedCallback = function(value) { PageMethods._staticInstance.set_defaultFailedCallback(value); }
PageMethods.get_defaultFailedCallback = function() { return PageMethods._staticInstance.get_defaultFailedCallback(); }
PageMethods.set_path(\"/signal_demo.aspx\");
PageMethods.FormatName= function(featureIds,onSuccess,onFailed,userContext) {PageMethods._staticInstance.FormatName(featureIds,onSuccess,onFailed,userContext); }
//]]>
</script>

<div>

      <input type=\"hidden\" name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\" value=\"/wEWBQK6lI3zAQLcteSgAQKQo8KrDQLs0bLrBgKlzeSLB5WD/E4S3+cgUPrYOjiWJ0/INDlN\" />
</div>
        <input type=\"hidden\" name=\"hdnReturnValue\" id=\"hdnReturnValue\" value=\"xx\" />
        <input type=\"hidden\" name=\"HiddenField1\" id=\"HiddenField1\" />
        <input name=\"TextBox1\" type=\"text\" id=\"TextBox1\" />
        <input name=\"hiddnvalue\" type=\"hidden\" id=\"hiddnvalue\" />
        <script type=\"text/javascript\">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('yourScriptManager', document.getElementById('form1'));
Sys.WebForms.PageRequestManager.getInstance()._updateControls([], [], [], 90);
//]]>
</script>

   

<script type=\"text/javascript\">
//<![CDATA[
Sys.Application.initialize();
//]]>
</script>
</form>
</body>
</html>
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33479129
lol you don't post it in code snipet...

could you post the webservice you're using ?
and the main page.

it's not a correct inetegration of the code, you should get back a light XML with the result
0
 

Author Comment

by:AbebeDemeke
ID: 33479228
the web service is the web method . isn't it ? if so it is the following

[WebMethod]
public List<String> FormatName(string featureIds)
{
            string[] rawdata = featureIds.Split(new char[] { ',' });

            List<String> strings = new List<String>();
            for (int i = 0; i < rawdata.Length; i++)
            {
                strings.Add(rawdata[i]);
            }
            return strings;
}

now when u say the main page if u mean the code where i called the web service it is like


    if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
       
      xmlhttp.open("POST","signal_demo.aspx/FormatName",false);
     
      xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      xmlhttp.send(encodeURI("featureIds=" + ids));
     
      document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;


or does it look like back to square one
? lol

please help me
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33479260
Did you really create a webservice page named : signal_demo.aspx

Or you're using the same previous page doing the call ?
0
 

Author Comment

by:AbebeDemeke
ID: 33479330
that is a good question. the signal_demo is the name of the page that contains the webmethod in its code behind
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33479355
create a dedicated webservice
0
 

Author Comment

by:AbebeDemeke
ID: 33479571
man I think you are taking me towards the solution after creating the dedicated webservice and doing

 if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
       
      xmlhttp.open("POST","Dedicated.asmx/FormatName",false);
     
      xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      xmlhttp.send(encodeURI("featureIds=" + ids));
     
      document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseText;



However the last line is returning an error message and I saw the xmlhttp.responseText and I found a much shorter xml document than the one above. lol

            xmlhttp.responseText      "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<string xmlns=\"http://tempuri.org/\">104,103,98,26,105</string>"      String

how can i extract the string containing the numbers  from the xml document?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33479600
yes you got a valid answer !

Please post it in code snipet, as you can see its not well formated in comment

to insert in code snipet, click on the Code link

___below me_____
0
 

Author Comment

by:AbebeDemeke
ID: 33479620
xmlhttp.responseText      "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<string xmlns=\"http://tempuri.org/\">104,103,98,26,105</string>"      String
0
 

Author Comment

by:AbebeDemeke
ID: 33479629
how can i extract the string value then?
xmlhttp.responseText      "<?xml version=\"1.0\" encoding=\"utf-8\"?>

<string xmlns=\"http://tempuri.org/\">104,103,98,26,105</string>"      String

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 33479655
:o(

try again, you post it again in comment
check bhind comment textarea, on the bottom left, you have links : File, Code, Image
Click on Code, paste you xml in the new textarea and click on the attach button

or confirm this is all you have :


<?xml version=\"1.0\" encoding=\"utf-8\"?>
<string xmlns=\"http://tempuri.org/\">104,103,98,26,105</string>

Open in new window

0
 

Author Comment

by:AbebeDemeke
ID: 33479695
that is all i have as an xmlhttp.responseText and I know that the value returned is a string containgin 104,103,98,26,105. but how can i extract it from the xml ?
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 33479747
>but how can i extract it from the xml ?
Use : xmlhttp.responseXML.getElementsByTagName("string")[0].childNodes[0].nodeValue
function webMethodCaller( ids){
     if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     xmlhttp.open("POST","Dedicated.asmx/FormatName",false);
     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     xmlhttp.send(encodeURI("featureIds=" + ids));
     document.getElementById("<%= HiddenField1.ClientID %>").innerHTML = xmlhttp.responseXML.getElementsByTagName("string")[0].childNodes[0].nodeValue;
}

Open in new window

0
 

Author Comment

by:AbebeDemeke
ID: 33479903
leakim971:

I think with your great help two days of hell is comming to a conclusion . I really apreciate your help . I really do. I hope we will meet in the future and I like to learn more from you. Thank you
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33479957
You're very welcome! Thanks for the points!

Hey! Look what you did lol :
tshirt.jpg
0
 

Author Comment

by:AbebeDemeke
ID: 33484745
leakim971:Everything is working fine except that when i try to pass multiple parametrs to the webmethod an error will be gnerated. I used the following approach to send multiple params.

 xmlhttp.send(encodeURI("featureIds="+ids&"sender="+senders));

senders is a simple string and I have also modified the web method to accept two string parms.

0
 
LVL 82

Expert Comment

by:leakim971
ID: 33484772
not : xmlhttp.send(encodeURI("featureIds="+ids&"sender="+senders));
but : xmlhttp.send(encodeURI("featureIds="+ids+"&sender="+senders));
0
 

Author Comment

by:AbebeDemeke
ID: 33484855
perfect. it works. thankyou
0
 
LVL 82

Expert Comment

by:leakim971
ID: 33484862
np
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now