2

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")           
    });
}
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
chris
  • 77
  • 1
  • 8

4 Answers4

4

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.

Community
  • 1
  • 1
Aidiakapi
  • 6,034
  • 4
  • 33
  • 62
  • Thanks Aidiakapi, but how would i do it with just calling the method rather than the webservice? – chris Mar 03 '11 at 16:34
  • Even tough I wouldn't advise it, it's in the first link in the answer: http://stackoverflow.com/questions/1176603/using-jquerys-getjson-method-with-an-asp-net-web-form/1190225#1190225 The reason why I wouldn't advise it is because it's again the web standards, using a WebService you follow all standards defined, using a direct method you're not doing that. But it works, and I suppose that's most important. – Aidiakapi Mar 03 '11 at 16:39
  • ok i will refer to that, i have enough libraries as it is. i thought it was only pertinent to use a webservice if some outside party needed to consume the information.. – chris Mar 03 '11 at 16:45
  • Well, a web service has the advantage of being usable by other parties, but as it's name says it serves data, and where that data is served to, doesn't really matter. – Aidiakapi Mar 03 '11 at 16:53
0

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/

madmik3
  • 6,975
  • 3
  • 38
  • 60
0

Maybe your solution is to use load():

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

Achilleterzo
  • 742
  • 6
  • 16
0

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

Community
  • 1
  • 1
Fabio
  • 3,020
  • 4
  • 39
  • 62