Solved

call webmethod from asp.net page

Posted on 2013-01-19
15
1,392 Views
Last Modified: 2013-02-05
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            string hasta_adi = e.CommandArgument.ToString();
            
            // Write code to delete data from SQL
            // if this patient will be deleted what should be done is 
            //\\//\\//\\//\\//\\//\\//\\\//\\/\\/\\/\/\/\/\/
            bool i = checkpatientexists(hasta_adi);

            //if i is true that means operations exist with this patient ,warn the user again 
            //if user confirms again then proceed with deletion. !!!

         if (i == true)
         {
          // System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> if(confirm('Hastaya ait operasyon(lar) bulunmaktadir gene de silmek istiyor musunuz?')==true){document.writeln('true');}else{document.writeln('false')}</SCRIPT>");
         
             Button btnDelete = e.Item.FindControl("btnDelete") as Button;

         // btnDelete.Attributes.Add("onclick", "return confirm('Hastaya ait operasyon(lar) bulunmaktadir gene de silmek istiyor musunuz?')");
         //  System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> confirm('Hastaya ait Operasyonlar bulunmaktadir...'+ btnDelete.CommandArgument.ToString()) </SCRIPT>");
         //  Response.Write("pressed OK");
          
          // System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> alert('Hit OK')</SCRIPT>");

         System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> if(confirm('Hastaya ait Operasyonlar bulunmaktadir ==>>" + btnDelete.CommandArgument.ToString() + "')==true){ PageMethods.M1(); };</SCRIPT>");
             
         //System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> confirm('" + btnDelete.CommandArgument.ToString() + "'adli hastaya ait operasyon(lar) bulunmaktadir...');</SCRIPT>");
         }
        }
    }
    [WebMethod]
    public static void  M1()
    {
        System.Web.HttpContext.Current.Response.Write("CAME TO WEB METHOD?");
        }

Open in new window




I have an asp.net application
 from the codebehind i want to call a webmethod but unfortunately i get the run time error as in the attached file.

what should i do to achieve to do a call to this web method?
runtime.JPG
0
Comment
Question by:nicedone
  • 6
  • 5
  • 2
  • +1
15 Comments
 
LVL 35

Expert Comment

by:Miguel Oz
ID: 38797585
The error is  java script error. The  best way to call a web method from java script is using Jquery, check:
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
0
 

Author Comment

by:nicedone
ID: 38798691
I will check it in to do it in jquery but as far as i know it is also possible to do it in JavaScript No? And if the error is in JavaScript what is it?tnx for the Comments anyways
0
 
LVL 21

Expert Comment

by:masterpass
ID: 38799473
Ref this : http://www.experts-exchange.com/Programming/Languages/Scripting/AJAX/A_2575-NET-AJAX-callbacks-to-ASPX-Pages.html

one thing that wont work in your code is System.Web.HttpContext.Current.Response.Write("CAME TO WEB METHOD?");

you can instead pass a string and then display in the onsuccess of the pagemethod.

Happy coding :)
0
 
LVL 35

Expert Comment

by:Miguel Oz
ID: 38799546
I did in Javascript before , in fact the link in the previous comment contains code using javascript only (See "What about the ScriptManager and EnablePageMethods?")
, but it is an awful/hard to read implementation compare with the clean/clear JQuery implementation.
0
 
LVL 10

Expert Comment

by:Monica P
ID: 38809806
try something like this
Wrap all your methods to be called via PageMethods in a class (may be defined as static) as:
public class Class1
{
        public Class1()
        {
                //
                // TODO: Add constructor logic here
                //
        }

    public static string TestAJAX(string Values)
    {

        if (Values == "Del")
            return "Delete Successfully ALl In One";
        else
            return "Could not delete Entry kdsafkda";
    }

}

Open in new window



Then call required methods from your PageMethod as:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static string TestAJAX(string Values)
    {
        return Class1.TestAJAX(Values);
    }
}

Open in new window

0
 
LVL 10

Expert Comment

by:Monica P
ID: 38809836
If you are getting PageMethods Is Undefined Error while using AJAX in ASP.NET or using a webservice than you need to check these things to resolve the issue

1. PageMethods needs to be static
[WebMethod]
public static int MethodName()
{
}

Open in new window


2. Enable pageMethods in scriptManager
<asp:ScriptManager ID="ScriptManager1" runat="server" 
                   EnablePageMethods="true">
</asp:ScriptManager>

Open in new window


3. add reference to script service in code behind
Add [Microsoft.Web.Script.Services.ScriptMethod] or
[System.Web.Script.Services.ScriptService] in code behind below [WebMethod] 

WebMethod] 
[Microsoft.Web.Script.Services.ScriptMethod]
public static string GetValues()  
{  
//DO something  
}

Open in new window

0
 

Author Comment

by:nicedone
ID: 38823106
@by: AkilaPalanimuthu

I did what you suggested but unfortunately it still gets the undefined error my friend :(
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:nicedone
ID: 38823237
@masterpass

you said

one thing that wont work in your code is System.Web.HttpContext.Current.Response.Write("CAME TO WEB METHOD?");

but i still get undefined error altough i took your reference as a guide so what should i do ?

    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Delete")
        {
            string hasta_adi = e.CommandArgument.ToString();
            
            // Write code to delete data from SQL
            // if this patient will be deleted what should be done is 
            //\\//\\//\\//\\//\\//\\//\\\//\\/\\/\\/\/\/\/\/
            bool i = checkpatientexists(hasta_adi);

            //if i is true that means operations exist with this patient ,warn the user again 
            //if user confirms again then proceed with deletion. !!!

         if (i == true)
         {
          // System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> if(confirm('Hastaya ait operasyon(lar) bulunmaktadir gene de silmek istiyor musunuz?')==true){document.writeln('true');}else{document.writeln('false')}</SCRIPT>");
         
             Button btnDelete = e.Item.FindControl("btnDelete") as Button;

         // btnDelete.Attributes.Add("onclick", "return confirm('Hastaya ait operasyon(lar) bulunmaktadir gene de silmek istiyor musunuz?')");
         //  System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> confirm('Hastaya ait Operasyonlar bulunmaktadir...'+ btnDelete.CommandArgument.ToString()) </SCRIPT>");
         //  Response.Write("pressed OK");
          
          // System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> alert('Hit OK')</SCRIPT>");

          System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> if(confirm('Hastaya ait Operasyonlar bulunmaktadir ==>>" + btnDelete.CommandArgument.ToString() + "')==true){ PageMethods.M1(); };</SCRIPT>");
             
         //System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> confirm('" + btnDelete.CommandArgument.ToString() + "'adli hastaya ait operasyon(lar) bulunmaktadir...');</SCRIPT>");
         }
        }
    }
    [System.Web.Services.WebMethod]
    [ScriptMethod]
    public static void  M1()
    {
       // System.Web.HttpContext.Current.Response.Write("CAME TO WEB METHOD?");
        string s = "Fatih Dikili";

        //return Class1.M2();
    }

Open in new window

0
 
LVL 21

Expert Comment

by:masterpass
ID: 38823379
can you please post the relevent asp page markup too ?
0
 
LVL 21

Expert Comment

by:masterpass
ID: 38823384
as a suggestion .. try to return a string value and display an alert  on the onSuccess of the js function call
0
 

Author Comment

by:nicedone
ID: 38824531
Hi,

I sent you the generated page ,when you hit DEL button on that page it tells me if i want to delete
if i say okey then it checks whether it has operations for that patient
if yes it asks it has operations do i still want to delete
if i hit yes again i get undefined error as i mentioned earlier,

As you see i call the function that way

System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> if(confirm('Hastaya ait Operasyonlar bulunmaktadir ==>>" + btnDelete.CommandArgument.ToString() + "')==true){ PageMethods.M1(); };</SCRIPT>");

Open in new window


can you help me with this code adding onsuccess and if onsuccess i will do a deletion operation from the database with a command ,how can i achieve it can you help with the code a little?
auto.html
0
 
LVL 21

Expert Comment

by:masterpass
ID: 38825439
I need he aspx markup page .. not the generated html .. and please post that on a txt file.
0
 

Author Comment

by:nicedone
ID: 38852538
I apologize for the late reply:

here is the page i also put that in the text file too

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Hastasil.aspx.cs" Inherits="Hastasil" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server" >
    <table>
<tr><td><asp:Button ID="Button1"  runat="server" Text="x" /></td><td>
    &nbsp;</td></tr>
<tr><td></td><td>&nbsp;</td></tr>
<tr><td></td><td></td></tr>
<tr><td></td>
<td> </td>

<td>
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand" OnItemDataBound="Repeater1_ItemDataBound">
  
    <ItemTemplate>

   <table>
   <tr>
   <td>
        <%#DataBinder.Eval(Container.DataItem, "hasta_adi")%>
    </td>
   <td><asp:Button ID="btnDelete" runat="server" CommandName="Delete" CommandArgument=<%#DataBinder.Eval(Container.DataItem,"hasta_adi")%> Text="DEL" />
   </td>
    <!-- <button onclick="confirm('Do you really want to delete?...');">DEL</button>-->
   
  
   <td>

   </td>
    </tr>
    </table>
    </ItemTemplate>
    </asp:Repeater>
</td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td>
    &nbsp;</td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
</table>
</asp:Content>

Open in new window

delete.txt
0
 
LVL 21

Accepted Solution

by:
masterpass earned 500 total points
ID: 38853195
took me a while to understand the real issue here. Like I said in one of the first post, I think,

System.Web.HttpContext.Current.Response.Write is what is playing up here

When you do a System.Web.HttpContext.Current.Response.Write it is executed as a response to your current request and as such your pagemethods in your html is not visible to this response, hence giving you error.

A best approach would be,

1.on item_databound event of repeater, loop through each button and determine whether or not to show the del button in that case
2.If you decide to show del button, assign an onclientclick event to that button along with the and pass the key to javascript
3.now write the js function in aspx page, ask for confirmation, and once confirmed - since you already have the key to that record, call the pagemethods with the key and then delete

find below a pseudo-code

Itemdatabound event
----------------------
Button btnDelete = e.Item.FindControl("btnDelete") as Button;
btnDelete.Attributes.Add("OnClientClick", "return somefunction('"+value of commandargument here +"');");


HTML
---------
function somefunction(value){
//ask for confirmation
//if yes call pagemethods

}

pagemethods
------------

[WebMethod]
public static void  M1(string value)
{
  //get value and delete 
}

Open in new window

0
 

Author Closing Comment

by:nicedone
ID: 38855374
Thank you
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

747 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

10 Experts available now in Live!

Get 1:1 Help Now