C#UserControl上的Jquery .ajax异步回发

我正在努力向项目系统添加待办事项列表,并希望todo创建触发异步回发以更新数据库。 我真的想在一个用户控件中托管这个,所以我可以将todo列表放到项目页面,任务页面或独立的待办事项列表页面上。

这就是我所拥有的。

用户控件“TodoList.ascx”,它位于Controls目录中。

位于UserControl顶部的脚本。 你可以看到我开始构建jsonText到回发的位置,但是当它不起作用时我只是尝试回发一个空数据变量并从AddTodo2方法中删除’string [] items’变量。

 $(document).ready(function() { // Add the page method call as an onclick handler for the div. $("#divAddButton").click(function() { var jsonText = JSON.stringify({ tdlId: 1, description: "test test test" }); //data: jsonText, $.ajax({ type: "POST", url: "TodoList.aspx/AddTodo2", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { alert('retrieved'); $("#divAddButton").text(msg.d); }, error: function() { alert("error"); } }); }); }); 

ascx上的其余代码。

 
Description
Active
Access Level
Add Todo

为了测试这个想法,我创建了一个位于根目录中的/TodoList.aspx页面。

  

todolist.aspx的cs

  protected void Page_Load(object sender, EventArgs e) { SecurityManager sm = new SecurityManager(); sm.MemberLevelAccessCheck(MemberLevelKey.AreaAdmin); } public static string AddTodo2() { return "yea!"; } 

我希望我可以拥有一个可用于显示多个待办事项列表的控件,并创建一个全新的待办事项列表。

当我点击#divAddButton时我可以看到它在firebug中构建回发但是一旦完成它就会通过警告“错误”来运行错误部分。 我不明白为什么。

我真的宁愿在用户控件中使用响应方法。 因为我将它放在几个页面上,以避免必须在每个页面上放置一个方法。

任何帮助,将不胜感激。


我无法使jquery ajax工作,所以我备份并尝试将div和jquery放在页面本身上并创建了一个webservice.asmx页面来处理回发。 我仍然从jquery返回错误,并想知道我是否配置错误或其他问题。

这是todo.aspx

   
Add Todo
$(document).ready(function() { // Add the page method call as an onclick handler for the div. $("#divAddButton").click(function() { var jsonText = JSON.stringify({ Todo: { TodoId: 1, Description: "test test test"} }); //var jsonTextEmpty = jsonText.stringify({""}); $.ajax({ type: "POST", url: "WebService.asmx/HelloWorld", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { alert('retrieved'); $("#divAddButton").text(msg); }, error: function() { alert("error"); } }); }); });

webservice.asmx与Visual Studio创建的默认位相同。 有没有办法找出导致错误的原因?

为了在您描述的jQuery中执行此操作,您需要将其发送到ASPX.cs文件中的装饰方法,您不能直接发送到.ascx方法。 好消息是aspx.cs方法可以调用ascx,因此它非常简单,您可以将它作为传递给它。

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

在aspx.cs的末尾,或者放在你的类中的另一个类库中,它知道如何解码这些东西:

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

ajax调用略有变化:

 $("#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"); } }); });