How to call code behind method from a javascript f

2020-07-26 07:17发布

问题:

I am having an javascript function for a HTML img click event in aspx page. And a server Method in its code behind page.Now I want to call the server method from the javascript function without any parameter only when the HTML img is clicked by the user.

C# Code Behind Method:

[WebMethod]
public void PopUpClick(object sender, EventArgs e)
{
    //Something;
}

JavaScriptMethod:

 $(document).ready(function () {

    $('.clickme').click(function () {
        PageMethods.PopUpClick();
    });

});

Also I added into the master page: <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" EnablePageMethods="true" />

It is not working.When I debugging this Javascript function on the Chrome I saw an error:Uncaught Reference Error:PageMethods is not defined.

回答1:

.aspx

     <div>
        <p>Say bye-bey to Postbacks.</p>

        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
        <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" />
    </div>

JavaScript

<script type="text/javascript">
        function HandleIT() {
            var name = document.getElementById('<%=txtname.ClientID %>').value;
            var address = document.getElementById('<%=txtaddress.ClientID %>').value;
            PageMethods.ProcessIT(name, address, onSucess, onError); 
            function onSucess(result) {
                alert(result);
            }
            function onError(result) {
                alert('Something wrong.');
            }
        }
    </script>

C#

 [WebMethod]
    public static string ProcessIT(string name, string address)
    {
        string result = "Welcome Mr. " + name + ". Your address is '" + address + "'.";
        return result;
    }


回答2:

The WebMethods that are defined must be "static".

The following ajax call to a WebMethod "GetAllRegions" works fine, provided, the WebMethod is defined as static!!

$.ajax({
  type: "POST",
  url: 'GenerateEAInHtml.aspx/GetAllRegions',
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
});

The WebMethod is defined this way:

[WebMethod]
public static List<Region> GetAllRegions()
{
  /* Your Code goes here */
  return regions;
}

You might want to use this Ajax Post to also pass JSON data to the WebMethod by passing the data parameter!! This should help.



回答3:

Assumption that your page name is abc.aspx and xyz is the function name that you have to call. javascript :


function sendData(offset) {
    $.ajax({
    type: "POST",
    url: "abc.aspx/xyz",
    contentType: "application/json; charset=utf-8",
    dataType: "json"
    });
}

Server Side : add Imports System.Web.Script.Serialization


WebMethod(enableSession:=True) _
Public Shared Function xyz() As String
    your code here
End Function

Add module in web.config -> system.webServer


->system.webServer>
    ->modules>
    ->add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    ->/modules>
->/system.webServer>



回答4:

Back end C# code is separate from your front end JavaScript code. JS runs on the client side and C# runs server side. In order to have front end code fire off a back end functions, you would either need your function to do a form postback or use Ajax (or an equivalent) to call that pages function.



回答5:

Try this

[WebMethod]

  public static void PopUpClick(object sender, EventArgs e)
    {
        //Something;
    }


回答6:

Use an ImageButton. The handler does not need to be tagged as [WebMethod]

<asp:ImageButton runat="server" ID="btnPopUp" ImageUrl="img.png" OnClick="PopUpClick" />

Why do you want to use img directly?



回答7:

There is a line at the top that says uncomment this to call it by JavaScript.

Uncomment that.

Then also add a [ScriptMethod] to your method like this:

[WebMethod]
[ScriptMethod]
public void PopUpClick(object sender, EventArgs e)
{
    // Something;
}

You should then be able to call it from the PageMethods object.

However I've just done some research and it seems that you may need to place your code that uses PageMethods at the end / after the ScriptManager as its possible you are trying to use PageMethods before its been declared in the JavaScript. Alternatively if you're using jQuery then you can do it in the ready event so you know the page and everything has loaded. I think this will probably turn out to be the root cause.



回答8:

A web method has to be declared as static and public.

Although you can't access the page directly, you can either pass what you need into the web method from the call in your client side code, or store what you need in session or a similar state storage mechanism that is accessible from your static web method.

That may require re-thinking what you're trying to do with it.