þÍńķ
þÍńķ

Reputation: 363

How to call a UserControls CodeBehind method from Jquery in ASP.NET?

Iam having a UserControl for showing Success/Warning/Error message. For all these kind of messages we have one UserControl "Message.ascx" Currently using for other aspx pages without Jquery

As we are trying to maintain standard message alerts. Now as iam using Jquery and JSON calls in my aspx page for the first time., i want to show these success message from my jquery.,

In general aspx codebehind i have used the User control as

//register User Control
<UM1:UM runat="server" ID="Message" /> 
 ....
 public void insert(){
 .. Some logic.., after success
 Message.ShowSuccess(" Inserted Successfully");
 }

But here in Jquery how do i call these ShowSuccess() which is in ascx.cs my ajax call

     $.ajax({
                 type: "POST",
                 contentType: "application/json; charset=utf-8",
                 url: "Voyage.aspx/Context_Update",
                 data: "{'ID':''1}",
                 dataType: "html",
                 success: function (html) {
                     try {                          
                        // Want to Show    Message.ShowSuccess(" Inserted Successfully");                     
                     } catch (ex) {
                         alert("ErrCode:1");
                     }

Iam not getting any idea and have not found any results too.., Please help me out

Upvotes: 1

Views: 4568

Answers (1)

Belogix
Belogix

Reputation: 8147

You can't make a call to a User-Control in ASP .NET as it isn't something that is directly served to the outside world but instead something that the server combines into your page during the page life-cycle.

If you want to call something on the server you need to add the [WebMethod] attribute to the server side method, this allows you to call from jQuery. You could have a [WebMethod] on your page that then calls some code in your User-Control, but not directly access your User-Control.

So, something like this:

MyPage.aspx

[WebMethod]
public static string GetMessageFromWebPage()
{
    return MyUserControl.GetMessageFromUserControl();
}

MyUserControl.ascx

public static string GetMessageFromUserControl()
{
    return "Hello World!"
}

jQuery

$.ajax({
  type: "POST",
  url: "MyPage.aspx/GetMessageFromWebPage",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something with the page method's return.
    $("#Result").text(msg.d);
  }
});

Upvotes: 2

Related Questions