如何使用 javascript 调用 ASP.NET c# 方法 [英] how to call an ASP.NET c# method using javascript

查看:24
本文介绍了如何使用 javascript 调用 ASP.NET c# 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何使用 javascript 调用服务器端的 c# 方法?如果选择取消,我需要做的是停止导入,或者如果选择确定则继续导入.我使用 Visual Studio 2010 和 C# 作为我的编程语言

这是我的代码:

private void AlertWithConfirmation(){响应.写("<script type="text/javascript">"+"if (window.confirm('导入正在进行中.你想继续导入吗?如果是选择确定,如果不是选择取消')) {" +"window.alert('导入已被取消!');"+"} 其他 {" +"window.alert('导入仍在进行中');"+"}" +"</脚本>");}

解决方案

PageMethod 一种更简单、更快捷的 Asp.Net AJAX 方法通过释放 AJAX 的强大功能,我们可以轻松改善 Web 应用程序的用户体验和性能.我在 AJAX 中最喜欢的东西之一是 PageMethod.

PageMethod 是一种我们可以在 java 脚本中公开服务器端页面方法的方法.这给我们带来了很多机会,我们可以在不使用缓慢且烦人的回发的情况下执行大量操作.

在这篇文章中,我将展示 ScriptManager 和 PageMethod 的基本用法.在这个例子中,我创建了一个用户注册表,用户可以在其中注册他的电子邮件地址和密码.这是我将要开发的页面的标记:

<form id="form1" runat="server"><div><fieldset style="width: 200px;"><asp:Label ID="lblEmailAddress" runat="server" Text="电子邮件地址"></asp:Label><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label><asp:TextBox ID="txtPassword" runat="server"></asp:TextBox></fieldset><div>

<asp:Button ID="btnCreateAccount" runat="server" Text="Signup"/>

</表单>

要设置页面方法,首先您必须在页面上拖动一个脚本管理器.

</asp:ScriptManager>

另请注意,我更改了 EnablePageMethods="true".
这将告诉 ScriptManager 我将从客户端调用 PageMethods.

现在下一步是创建一个服务器端函数.
这是我创建的函数,该函数验证用户的输入:

[WebMethod]public static string RegisterUser(string email, string password){string result = "恭喜!!!您的账户已经创建.";if (email.Length == 0)//零长度校验{result = "邮箱地址不能为空";}else if (!email.Contains(".") || !email.Contains("@"))//其他一些基本检查{result = "不是一个有效的电子邮件地址";}else if (!email.Contains(".") || !email.Contains("@"))//其他一些基本检查{result = "不是一个有效的电子邮件地址";}否则如果(密码.长度== 0){result = "密码不能为空";}else if (password.Length <5){result = "密码不能少于5个字符";}返回结果;}

要告诉脚本管理器此方法可通过 javascript 访问,我们需要确保两件事:
第一:此方法应为公共静态".
第二:上面代码中写的方法上面应该有一个[WebMethod]标签.

现在我已经创建了创建帐户的服务器端函数.现在我们必须从客户端调用它.以下是我们如何从客户端调用该函数:

为了调用我的服务器端方法注册用户,ScriptManager 生成一个代理函数,该函数在 PageMethods 中可用.
我的服务器端函数有两个参数,即电子邮件和密码,在这些参数之后,我们必须再给出两个函数名称,如果方法成功执行(第一个参数,即 onSucess)或方法失败(第二个参数,即结果)将运行).

现在一切似乎都准备好了,现在我在我的注册按钮上添加了 OnClientClick="Signup();return false;".所以这里是我的 aspx 页面的完整代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="服务器"><title></title><身体><form id="form1" runat="server"><div><asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager><fieldset style="width: 200px;"><asp:Label ID="lblEmailAddress" runat="server" Text="电子邮件地址"></asp:Label><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label><asp:TextBox ID="txtPassword" runat="server"></asp:TextBox></fieldset><div>

<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;"/>

</表单><script type="text/javascript">函数注册(){var email = document.getElementById('<%=txtEmail.ClientID %>').value;var password = document.getElementById('<%=txtPassword.ClientID %>').value;PageMethods.RegisterUser(email, password, onSucess, onError);功能 onSucess(结果){警报(结果);}函数 onError(result) {alert('暂时无法处理您的请求,请稍后再试.');}}

Does anyone know how to call a server-side c# method using javascript? What i need to do is to stop imports if Cancel is chosen or to continue importing if ok is chosen. I am using visual studio 2010 and c# as my programming lanaguage

This is my code:

private void AlertWithConfirmation()            
{                 
    Response.Write(
        "<script type="text/javascript">" +     
            "if (window.confirm('Import is currently in progress. Do you want to continue with importation? If yes choose OK, If no choose CANCEL')) {" +     
                "window.alert('Imports have been cancelled!');" +     
            "} else {" +   
                "window.alert('Imports are still in progress');" +     
            "}" +      
        "</script>");   
}

解决方案

PageMethod an easier and faster approach for Asp.Net AJAX We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.

PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.

In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:

<body>
    <form id="form1" runat="server">
    <div>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup"  />
    </div>
    </form>
</body>
</html>

To setup page method, first you have to drag a script manager on your page.

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

Also notice that I have changed EnablePageMethods="true".
This will tell ScriptManager that I am going to call PageMethods from client side.

Now next step is to create a Server Side function.
Here is the function which I created, this function validates user's input:

[WebMethod]
public static string RegisterUser(string email, string password)
{
    string result = "Congratulations!!! your account has been created.";
    if (email.Length == 0)//Zero length check
    {
        result = "Email Address cannot be blank";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }

    else if (password.Length == 0)
    {
        result = "Password cannot be blank";
    }
    else if (password.Length < 5)
    {
        result = "Password cannot be less than 5 chars";
    }

    return result;
}

To tell script manager that this method is accessible through javascript we need to ensure two things:
First: This method should be 'public static'.
Second: There should be a [WebMethod] tag above method as written in above code.

Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods.
My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).

Now every thing seems ready, and now I have added OnClientClick="Signup();return false;" on my Signup button. So here complete code of my aspx page :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" />
    </div>
    </form>
</body>
</html>

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

这篇关于如何使用 javascript 调用 ASP.NET c# 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆