如何使用JavaScript来调用一个ASP.NET的C#方法 [英] how to call an ASP.NET c# method using javascript

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

问题描述

有谁知道如何调用使用JavaScript服务器端的C#方法?我需要做的是阻止进口,如果取消选择,或者如果确定是选择继续导入。我使用Visual Studio 2010和C#作为我的编程lanaguage

这是我的code:

 私人无效AlertWithConfirmation()
{
    回复于(
        <脚本类型= \\文/ JavaScript的\\>中+
            如果(window.confirm('导入目前正在进展中。是否要继续进口?如果是选择确定,如果没有选择取消')){+
                window.alert('进口量已经取消了!'); +
            }其他{+
                window.alert('进口仍在进行中'); +
            }+
        &所述; /脚本>中);
}


解决方案

对于PageMethod的AJAX Asp.Net一种更加简单快捷的方法
我们可以很容易地通过释放AJAX的力量改善用户体验和Web应用程序的性能。其中一个我在AJAX最喜欢的事情之一是PageMethod的。

PageMethod的是一个方法,通过它我们可以公开服务器端页面在Java脚本的方法。这带来这么多的机会,我们可以在不使用慢和恼人的背上后进行大量的操作。

在这篇文章中,我展示的基本使用的ScriptManager和PageMethod的的。在这个例子中,我创建一个用户登记表,其中用户可以对他的电子邮件地址和密码进行注册。这里是哪个网页,我要开发的标记: -

 <身体GT;
    <表ID =form1的=服务器>
    < D​​IV>
        <字段集的风格=宽度:200像素;>
            < ASP:标签ID =lblEmailAddress=服务器文本=电子邮件地址>< / ASP:标签>
            < ASP:文本框ID =txtEmail=服务器>< / ASP:文本框>
            < ASP:标签ID =lblPassword=服务器文本=密码>< / ASP:标签>
            < ASP:文本框ID =txtPassword=服务器>< / ASP:文本框>
        < /字段集>
        < D​​IV>
        < / DIV>
        < ASP:按钮的ID =btnCreateAccount=服务器文本=注册/>
    < / DIV>
    < /表及GT;
< /身体GT;
< / HTML>

要设置页面的方法,首先你必须拖动脚本管理你的页面上。

 < ASP:的ScriptManager ID =ScriptManager1=服务器的EnablePageMethods =真>
< / ASP:ScriptManager的>

另请注意,我已经改变的EnablePageMethods =真,这将告诉ScriptManager的,我打算从客户端调用页面方法。

现在下一步是创建一个服务器端的功能。下面是我创建的函数,这个函数验证用户的输入: -

  [的WebMethod]
公共静态字符串RegisterUser(字符串email,字符串密码)
{
    字符串结果=恭喜!您的帐户已创建。
    如果(email.Length == 0)//零长度检查
    {
        结果=电子邮件地址不能为空;
    }
    否则如果(!email.Contains(。)||!email.Contains(@))//一些其它基本检查
    {
        结果=不是一个有效的电子邮件地址;
    }
    否则如果(!email.Contains(。)||!email.Contains(@))//一些其它基本检查
    {
        结果=不是一个有效的电子邮件地址;
    }    否则,如果(password.Length == 0)
    {
        结果=密码不能为空;
    }
    否则如果(password.Length小于5)
    {
        结果=密码canonot少于5个字符;
    }    返回结果;
}

要告诉脚本管理器,这种方法是通过JavaScript,我们需要确保两件事访问。首先这种方法应该是公共静态。其次应该有上述方法[的WebMethod]标签写在上面code。

现在我已经创建服务器端函数创建帐户。现在,我们必须从客户端调用它。下面是我们如何可以调用该函数从客户端: -

 <脚本类型=文/ JavaScript的>
    功能注册(){
        VAR电子邮件=的document.getElementById('<%= txtEmail.ClientID%GT;')。值;
        VAR密码=的document.getElementById('<%= txtPassword.ClientID%GT;')。值;        PageMethods.RegisterUser(电子邮件,密码,onSucess,onError的);        功能onSucess(结果){
            警报(结果);
        }        功能onError的(结果){
            警报('无法处理您此刻的请求,请稍后再试。');
        }
    }
< / SCRIPT>

要叫我的服务器端方法注册用户,ScriptManager的生成代理功能这是PageMethods可用。我的服务器端函数有两个PARAMATERS即电子邮件地址和密码,该参数后,我们不得不放弃,如果执行成功的方法(第一个参数,即onSucess)或方法失败(第二个参数即结果),这将运行两个函数名。

现在一切事情都似乎准备好了,现在我已经添加的OnClientClick =注册();返回false;在我的注册按钮。我的aspx页面所以在这里完成code: -

 <!DOCTYPE HTML PUBLIC -  // W3C // DTD XHTML 1.0过渡// ENhttp://www.w3.org/TR/xhtml1/DTD/ XHTML1-transitional.dtd>
< HTML的xmlns =htt​​p://www.w3.org/1999/xhtml>
<头=服务器>
    <标题>< /标题>
< /头>
<身体GT;
    <表ID =form1的=服务器>
    < D​​IV>
        < ASP:的ScriptManager ID =ScriptManager1=服务器的EnablePageMethods =真>
        < / ASP:ScriptManager的>
        <字段集的风格=宽度:200像素;>
            < ASP:标签ID =lblEmailAddress=服务器文本=电子邮件地址>< / ASP:标签>
            < ASP:文本框ID =txtEmail=服务器>< / ASP:文本框>
            < ASP:标签ID =lblPassword=服务器文本=密码>< / ASP:标签>
            < ASP:文本框ID =txtPassword=服务器>< / ASP:文本框>
        < /字段集>
        < D​​IV>
        < / DIV>
        < ASP:按钮的ID =btnCreateAccount=服务器文本=注册的OnClientClick =注册();返回false; />
    < / DIV>
    < /表及GT;
< /身体GT;
< / HTML><脚本类型=文/ JavaScript的>
    功能注册(){
        VAR电子邮件=的document.getElementById('<%= txtEmail.ClientID%GT;')。值;
        VAR密码=的document.getElementById('<%= txtPassword.ClientID%GT;')。值;        PageMethods.RegisterUser(电子邮件,密码,onSucess,onError的);        功能onSucess(结果){
            警报(结果);
        }        功能onError的(结果){
            警报('无法处理您此刻的请求,请稍后再试。');
        }
    }
< / SCRIPT>

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 Page Methods 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 canonot 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆