繁体   English   中英

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

[英]Call C# method from another page in javascript function with jQuery

在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 Call刚刚发布的问题,我需要执行$ .get之类的事情吗?

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

看一下这个问题: 将jQuery的getJSON方法与ASP.NET Web窗体一起使用

它显示了如何做。

一个例子:

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>

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" %>

我希望这可以解释这个想法。

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

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

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 () {
            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。

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

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

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

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

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

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

ASP.NET-将JSON从jQuery传递到ASHX

[]的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM