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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18510749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:26:16  来源:igfitidea点击:

How to call code behind method from a javascript function?

c#javascriptasp.net.netscriptmanager

提问by user2729114

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.

我在 aspx 页面中有一个 HTML img 点击事件的 javascript 函数。和一个服务器方法在它的代码隐藏页面中。现在我想只在用户单击 HTML img 时从 javascript 函数调用服务器方法而没有任何参数。

C# Code Behind Method:

C# 代码隐藏方法:

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

JavaScriptMethod:

JavaScript方法:

 $(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 函数时,我看到一个错误:未捕获的引用错误:未定义页面方法。

回答by nphx

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

使用ImageButton。处理程序不需要标记为[WebMethod]

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

Why do you want to use img directly?

为什么要直接使用img?

回答by Nicholas Post

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.

后端 C# 代码与前端 JavaScript 代码是分开的。JS 在客户端运行,C# 在服务器端运行。为了让前端代码触发后端函数,您需要您的函数执行表单回发或使用 Ajax(或等效物)调用该页面函数。

回答by Tapas Mahata

Try this

尝试这个

[WebMethod]

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

回答by rtpHarry

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

顶部有一行表示取消注释 this 以通过 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 PageMethodsobject.

然后您应该能够从PageMethods对象中调用它。

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

但是,我刚刚做了一些研究,似乎您可能需要将使用的代码PageMethods放在最后/之后,ScriptManager因为它可能是PageMethods在 JavaScript 中声明之前尝试使用的。或者,如果您使用的是 jQuery,那么您可以在ready事件中执行此操作,以便您知道页面和所有内容都已加载。我认为这可能会成为根本原因。

回答by Sasidharan

.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;
    }

回答by Underground

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

必须将 Web 方法声明为静态和公共方法。

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.

这可能需要重新考虑你想用它做什么。

回答by sanrns

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!!

以下对 WebMethod“GetAllRegions”的 ajax 调用工作正常,前提是 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!! This should help.

您可能还想使用这个 Ajax Post 通过传递 data 参数将 JSON 数据传递给 WebMethod!这应该有帮助。

回答by Amnesh Goel

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

假设您的页面名称是 abc.aspx,而 xyz 是您必须调用的函数名称。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

服务器端:添加导入 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>