简体   繁体   English

如何从javascript函数调用代码隐藏方法?

[英]How to call code behind method from a javascript function?

I am having an javascript function for a HTML img click event in aspx page. 我在aspx页面中有一个HTML img click事件的javascript函数。 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. 并且在其代码后面的服务器方法页面。现在我想只在用户点击HTML img时从javascript函数调用服务器方法而不使用任何参数。

C# Code Behind Method: 方法背后的C#代码:

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

JavaScriptMethod: 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" /> 我也加入了母版页: <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. 它无法正常工作。当我在Chrome上调试此Javascript函数时,我看到一个错误:未捕获的参考错误:未定义PageMethods。

.aspx 的.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 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# C#

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

Assumption that your page name is abc.aspx and xyz is the function name that you have to call. 假设您的页面名称是abc.aspx和xyz是您必须调用的函数名称。 javascript : 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 服务器端:添加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 在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>

Back end C# code is separate from your front end JavaScript code. 后端C#代码与前端JavaScript代码分开。 JS runs on the client side and C# runs server side. JS在客户端运行,C#在服务器端运行。 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. 为了让前端代码触发后端函数,您需要使用函数来执行表单回发或使用Ajax(或等效函数)来调用该页面函数。

The WebMethods that are defined must be "static". 定义的WebMethod必须是“静态的”。

The following ajax call to a WebMethod "GetAllRegions" works fine, provided, the WebMethod is defined as static!! 以下ajax调用WebMethod“GetAllRegions”工作正常,只要WebMethod定义为静态!!

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

The WebMethod is defined this way: WebMethod以这种方式定义:

[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!! 您可能希望使用此Ajax Post通过传递数据参数将JSON数据传递给WebMethod! This should help. 这应该有所帮助。

Use an ImageButton . 使用ImageButton The handler does not need to be tagged as [WebMethod] 处理程序不需要标记为[WebMethod]

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

Why do you want to use img directly? 为什么要直接使用img?

Try this 尝试这个

[WebMethod]

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

There is a line at the top that says uncomment this to call it by JavaScript. 顶部有一行表示取消注释,以便通过JavaScript调用它。

Uncomment that. 取消注释。

Then also add a [ScriptMethod] to your method like this: 然后还为您的方法添加[ScriptMethod] ,如下所示:

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

You should then be able to call it from the PageMethods object. 然后,您应该能够从PageMethods对象中调用它。

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. 但是我刚做了一些研究,似乎你可能需要在ScriptManager的末尾/后面放置使用PageMethods的代码,因为你可能在JavaScript中声明之前尝试使用PageMethods Alternatively if you're using jQuery then you can do it in the ready event so you know the page and everything has loaded. 或者,如果您正在使用jQuery,那么您可以在ready事件中执行此操作,以便您知道页面并且所有内容都已加载。 I think this will probably turn out to be the root cause. 我认为这可能会成为根本原因。

A web method has to be declared as static and public. Web方法必须声明为static和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. 虽然您无法直接访问该页面,但您可以通过客户端代码中的调用将所需内容传递给Web方法,或者在会话中存储您需要的内容或可以从静态Web访问的类似状态存储机制方法。

That may require re-thinking what you're trying to do with it. 这可能需要重新思考你正在尝试用它做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM