使用jQuery从javascript函数中的另一个页面调用C#方法

使用jQuery从javascript函数中的另一个页面调用C#方法,c#,javascript,jquery,asp.net,C#,Javascript,Jquery,Asp.net,在GridViewData.aspx.cs中,我想在JavaCScript函数中调用一个方法 //This simple example method is from GridViewData.aspx.cs private int ValidateNameUpdateable() { return 22; } 我想从default.aspx中的Javascript调用此函数 <script type="text/javascript"> function

在GridViewData.aspx.cs中,我想在JavaCScript函数中调用一个方法

//This simple example method is from GridViewData.aspx.cs
private int ValidateNameUpdateable()
{
    return 22;   

}
我想从default.aspx中的Javascript调用此函数

<script type="text/javascript">
    function validateForm() 
    {            

        if (ValidateNameUpdateable==22) 
        {
            alert("Name is not updateable, the party already started.");
             return false;
        }

        //if all is good let it update
        UpdateInsertData()
    }
</script> 

看看这个问题:

它展示了如何做到这一点

例如:

Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    <!--
        $(function () {
            $.ajax({
                type: "POST",
                url: "WebService.asmx/ValidateNameUpdateable",
                data: "{\"input\":5}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    // (msg.d is the retrieved data)
                    var d = msg.d;
                    if (d == 22) {
                        alert("OK");
                    }
                    else {
                        alert("Not OK");
                    }
                },
                error: function (msg) {
                }
            });
        });
    //-->
    </script>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    <!--
        $(function () {
            function getRecord(id) {
                $.ajax({
                    type: "POST",
                    url: "WebService.asmx/GetRecord",
                    data: "{\"id\":" + id + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        // (msg.d is the retrieved data)
                        var d = $.parseJSON(msg.d);
                        if (d.RecordExists) {
                            alert("Record with id: " + d.ID + "\nFirstName: " + d.FirstName + "\nLastName: " + d.LastName);
                        }
                        else {
                            alert("Record doesn't exist.");
                        }
                    },
                    error: function (msg) {
                    }
                });
            }

            getRecord(1);
            getRecord(4);
            getRecord(0);
        });
    //-->
    </script>
</body>
</html>

WebService.cs(应用程序代码中):

使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用System.Web.Services;
/// 
///WebService的摘要描述
/// 
[System.Web.Script.Services.ScriptService]

[WebService(命名空间=”http://tempuri.org/“)]/我想您正在寻找ajax。它允许您对服务器进行异步调用并获得result。您应该创建一个简单的aspx页面,该页面包含一些请求参数并输出正确的信息。然后使用ajax调用load页面并获得结果

下面是ajax的基本概述

下面是jqueryajax调用
也许您的解决方案是使用load():


您不能直接这样做,例如,您需要通过httphandler(ashx)发布数据。然后处理程序返回一个json对象。你深入研究以找到你想要的答案


[]的

谢谢Aidiakapi,但是如果只调用方法而不是web服务,我该怎么做呢?即使很难,我也不会建议,答案中的第一个链接是:我之所以不建议,是因为它又是web标准,使用一个您遵循所有定义标准的web服务,用直接的方法你不会这么做。但它是有效的,我想这是最重要的。好的,我会参考它,我有足够的库。我认为只有当某个外部方需要使用信息时,才可以使用web服务。好吧,web服务的优点是可供其他方使用,但顾名思义,它提供数据,以及数据提供到何处并不重要。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "http://tempuri.org/")] // <-- Put something like: services.yourdomain.com in here.
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService {

    [WebMethod]
    public int ValidateNameUpdateable(int input)
    {
        return input == 5 ? 22 : -1;
    }
}
<%@ WebService Language="C#" CodeBehind="~/App_Code/WebService.cs" Class="WebService" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    <!--
        $(function () {
            function getRecord(id) {
                $.ajax({
                    type: "POST",
                    url: "WebService.asmx/GetRecord",
                    data: "{\"id\":" + id + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        // (msg.d is the retrieved data)
                        var d = $.parseJSON(msg.d);
                        if (d.RecordExists) {
                            alert("Record with id: " + d.ID + "\nFirstName: " + d.FirstName + "\nLastName: " + d.LastName);
                        }
                        else {
                            alert("Record doesn't exist.");
                        }
                    },
                    error: function (msg) {
                    }
                });
            }

            getRecord(1);
            getRecord(4);
            getRecord(0);
        });
    //-->
    </script>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;

/// <summary>
/// Summary description for WebService
/// </summary>
[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "http://tempuri.org/")] // <-- Put something like: services.yourdomain.com in here.
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService {

    [Serializable]
    protected class Record
    {
        public bool RecordExists { get; set; }
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Record() // Initializes default values
        {
            RecordExists = true;
            ID = 0;
            FirstName = "";
            LastName = "";
        }
    }

    [WebMethod]
    public string GetRecord(int id)
    {
        // Initialize the result
        Record resultRecord = new Record();
        resultRecord.RecordExists = true;
        resultRecord.ID = id;

        // Query database to get record...
        switch (id)
        {
            case 0:
                resultRecord.FirstName = "John";
                resultRecord.LastName = "Something";
                break;
            case 1:
                resultRecord.FirstName = "Foo";
                resultRecord.LastName = "Foo2";
                break;
            default:
                resultRecord.RecordExists = false;
                break;
        }

        // Serialize the result here, and return it to JavaScript.
        // The JavaScriptSerializer serializes to JSON.
        return new JavaScriptSerializer().Serialize(resultRecord);
    }
}