Jquery .ajax async postback on C# UserControl

后端 未结 1 1181
南笙
南笙 2020-12-20 08:46

I\'m working on adding a todo list to a project system and would like to have the todo creation trigger a async postback to update the database. I\'d really like to host th

相关标签:
1条回答
  • 2020-12-20 08:50

    In order to do this with jQuery as you describe, you need to sent it to a decorated method in your ASPX.cs file, you cannot send directly to the .ascx method. The good news is that the aspx.cs method can call the ascx one, so it is really pretty easy and you can just use it as a pass through to that.

    [WebMethod]
    public static string AddTodo2(myTodo todo2add)
    {
     //call your ascx method here
     mymethod(todo2add.td1Id,todo2add.description);
     return "yea!"; 
    }
    

    at the end of the aspx.cs, or in another class library put in your class so it knows how to decode the stuff:

    public class myTodo
       {
           /// <summary>
           /// web service/webmethod needs 0 parameter constructor
           /// </summary>
           public myTodo()
           {
           }
           public myTodo(int tdlId, string description)
           {
               TdlId= tdlId;
               Description= description;
           }
    
           public int TdlId;
           public string Description;
    
       }
    

    slight change to the ajax call:

    $("#divAddButton").click(function() {                
       var jsonText = JSON.stringify({myTodo:{ tdlId: 1, description: "test test test" }});
       $.ajax({               
           type: "POST",                
           url: "TodoList.aspx/AddTodo2",                
           data: jsonText,                
           contentType: "application/json; charset=utf-8",                
           dataType: "json",                
           success: function(msg) {                
              alert('retrieved');                
           $("#divAddButton").text(msg.d);                
           },                
           error: function() {                
                 alert("error");                
                 }                
       });                
    }); 
    
    0 讨论(0)
提交回复
热议问题