简体   繁体   中英

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

In GridViewData.aspx.cs I have a method I want to call inside a javacsript function.

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

}

I want to call this function from Javascript in default.aspx

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

Now hears the kicker, I am mostly using jqUery as UpdateInsertData() is a jquery Call and works fine. How do I use ValidateNameUpdateable to call jQuery to return the value from the c# method. . I believe this issue is with my jQuery Call as its just posting and I need to do a $.get or something?

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

Take a look at this question: Using jQuery's getJSON method with an ASP.NET Web Form

It shows how to do it.

An example:

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

I hope this explains the idea.

If you want to be able to pass more advanced structures (no int, or string) you might want to consider using JSON.
For the parsing of JSON I'll use the JQuery function parseJSON

All you need to do is create a structure on the web service (struct), and serialize it using the JSON serializer.
Another example using 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);
    }
}

Please note that AJAX is Asynchronous, that means that even tough the pages are requested in a specific order, they are not received in a specific order. That means that even tough you request the records in order: 1, 4, 0, they can be received in any order, like 4, 1, 0, or 1, 0, 4.

I think you are looking for ajax. It lets you make asynchronous calls to a server and get the restult. You should make a simple aspx page that takes some request arguments and outputs the correct information. Then use ajax to call load that page and get the results.

here is a basic overview of ajax http://www.prototypejs.org/learn/introduction-to-ajax

Here is the jQuery ajax call http://api.jquery.com/jQuery.ajax/

Maybe your solution is to use load():

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

You can't do it directly, you need to post your data through an httphandler (ashx), for example. Then your handler returns a json object. You delve into to find the response you want.

ASP.NET - Passing JSON from jQuery to ASHX

[]'s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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