【问题标题】:Call C# method from another page in javascript function with jQuery使用 jQuery 在 javascript 函数中从另一个页面调用 C# 方法
【发布时间】:2011-03-03 15:41:44
【问题描述】:

在 GridViewData.aspx.cs 中,我有一个要在 javacsript 函数中调用的方法。

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

现在听到踢球了,我主要使用 jqUery,因为 UpdateInsertData() 是一个 jquery 调用并且工作正常。如何使用 ValidateNameUpdateable 调用 jQuery 从 c# 方法返回值。 .我相信这个问题与我刚刚发布的 jQuery 调用有关,我需要执行 $.get 或其他操作吗?

function ValidateNameUpdateable() 
{
    $(document).ready(function () 
    {
        $.post("GridViewData.aspx")           
    });
}

【问题讨论】:

    标签: c# javascript jquery asp.net


    【解决方案1】:

    看看这个问题: Using jQuery's getJSON method with an ASP.NET Web Form

    它显示了如何做到这一点。

    一个例子:

    默认.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>
    

    WebService.cs(在 App_Code 中):

    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.asmx:

    <%@ WebService Language="C#" CodeBehind="~/App_Code/WebService.cs" Class="WebService" %>
    

    我希望这能解释这个想法。

    如果您希望能够传递更高级的结构(非整数或字符串),您可能需要考虑使用 JSON。
    对于 JSON 的解析,我将使用 JQuery 函数 parseJSON

    您需要做的就是在 Web 服务(结构)上创建一个结构,并使用 JSON 序列化器对其进行序列化。
    另一个使用 JSON 的例子:

    默认.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 () {
                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:

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

    请注意,AJAX 是异步的,这意味着即使页面是按特定顺序请求的,它们也不是按特定顺序接收的。这意味着即使您按 1、4、0 的顺序请求记录很困难,也可以按任何顺序接收它们,例如 4、1、0 或 1、0、4。

    【讨论】:

    • 感谢 Aidiakapi,但我将如何只调用方法而不是 web 服务呢?
    • 即使很难,我也不建议这样做,它在答案的第一个链接中:stackoverflow.com/questions/1176603/… 我不建议这样做的原因是因为它又是网络标准,使用 WebService 你遵循所有定义的标准,使用直接的方法,你没有这样做。但它有效,我认为这是最重要的。
    • 好的,我会提到,我有足够的库。我认为只有在某些外部方需要使用信息时才使用网络服务。
    • 嗯,Web 服务的优点是可供其他方使用,但顾名思义,它提供数据服务,以及将数据服务到哪里并不重要。
    【解决方案2】:

    我认为您正在寻找 ajax。它使您可以对服务器进行异步调用并获得结果。您应该制作一个简单的 aspx 页面,该页面采用一些请求参数并输出正确的信息。然后使用 ajax 调用加载该页面并获取结果。

    这里是 ajax 的基本概述 http://www.prototypejs.org/learn/introduction-to-ajax

    这里是 jQuery ajax 调用 http://api.jquery.com/jQuery.ajax/

    【讨论】:

      【解决方案3】:

      也许您的解决方案是使用 load():

      http://api.jquery.com/load/

      【讨论】:

        【解决方案4】:

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

        ASP.NET - Passing JSON from jQuery to ASHX

        []的

        【讨论】:

          猜你喜欢
          • 2014-04-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-10-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多