1

I am developing an ASP.Net application where I'm running into some trouble calling a function in the code behind using JavaScript.

This is the JavaScript function I'm trying to run:

PageMethods.EditRecord($(this).data("row-id"));

And this is my code behind function:

public void EditRecord(string logID)
{
    lblLogID.Text = logID;

    ClientScript.RegisterStartupScript(GetType(), "Show", "<script> $('#edit').modal('toggle');</script>");
}

If I run it like this I get the following error:

Uncaught ReferenceError: PageMethods is not defined

I did some reading and realized that I'm supposed to change public void EditRecord(string logID) to public static void EditRecord(string logID).

Unfortunately, when I attempt that then lblLogID and ClientScript give me hassles with the following error:

An object reference is required for the non-static, method, or property...

How can I work around this to run my code behind method using JavaScript without all these drawbacks?

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143

1 Answers1

0

You need to use a success callback function.

In your script,

PageMethods.EditRecord($(this).data("row-id"), onSuccess);

function onSuccess(logId) { $("#"+"<%=lblLogId.ClientID%>").html(logId); }

In your aspx.cs,

[WebMethod] public static string EditRecord(string logID) { return logID; }

Answered from mobile device.

Hope this helps you to implement.

Note: It has to be static. You cannot use ASP.net controls in your static method. All you can do is, return whatever you want from the method and use it in JavaScript.

Anoop H.N
  • 1,244
  • 1
  • 15
  • 31