Click here to Skip to main content
15,887,336 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
i tried everything i could, but still no luck. where is my mistake?

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <title></title>
    <script type="text/javascript">
        function InsertLabelData() {
            PageMethods.GetLabelText(onSuccess, onFailure);
        }

        function onSuccess(result) {
            var lbl = document.getElementById('lbl');
            lbl.innerHTML = result;
        }

        function onFailure(error) {
            alert(error);
        }

        InsertLabelData();
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <label id="lbl"></label>
            <asp:ScriptManager ID="ScriptManager2" runat="server" EnablePageMethods="true" EnablePartialRendering="true">
            </asp:ScriptManager>


        </div>
    </form>
</body>
</html>


Default2.aspx.cs
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static string GetLabelText()
    {
        return "Hello";
    }
}
Posted

1 solution

Hii,

Well PageMethods have always been a controversial topic but I believe they will be called when you have an event attached to the control whihc you are using. In this case if you put a Javascript event such as 'onmouseover', then it works perfectly...

C#
ex:
<script type="text/javascript">

        function GetLabel() {
            PageMethods.GetLabelText(onsuccess, onfailure);
        }
        function onsuccess(result) {
            var x = document.getElementById('lblnew');
            x.innerHTML = result;
        }
        function onfailure(error) {
            alert(error);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <label id="lblnew" onmouseover="GetLabel();"> hiii</label>

        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>

    </div>
    </form>
</body>
</html>


aspx.cs:
C#
[System.Web.Services.WebMethod]
public static string GetLabelText()
{
    return "Dark Knight";
}


Calling a plain Javascript function won't work IMO because the label control doesnot know when to call it. Try like this and you will understand much stuffs.
Happy Coding...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900