如何使用WebForms更新投票客户端

我正在尝试实现与Stack Overflow非常类似的投票。 有多个项目旁边都有一个投票按钮。 目前,我有它工作,但它已完成服务器端,回发,并需要一段时间来重新加载数据。 这是流程:

  1. 你点击投票按钮,
  2. 它会触发一个javascript函数,它点击一个隐藏的ASP.NET按钮(这样做是因为每页有多个投票按钮),
  3. 按钮触发,
  4. 它更新数据库,然后
  5. 页面回发并刷新,显示更新。

如何利用javascript和AJAX消除这种糟糕的用户体验? 我希望它像Stack Overflow一样工作,但我没有使用MVC。 任何帮助,例子,建议都会很棒。 谢谢。

更新:

我实现了这个,但是当我在Web方法上放置断点时,它甚至不会触发,我总是得到错误警报。 有任何想法吗?

JavaScript的:

 $(document).ready(function () { $("[id^=VoteMeUp]").click(function (event) { var dta = '{ "VoteId":' + $(event.target).val() + '}'; $.ajax( { type: 'POST', data: dta, url: 'Default.aspx/SaveUpVote', contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { //$(event.target).text("Vote Casted"); alert("Vote Casted"); }, error: function (x, y, z) { alert("Oops. An error occured. Vote not casted! Please try again later."); } } ); }); });  

Code Behind(您可以使用C#,我对两者都很熟悉):

 Imports System.Web.Services Imports System.Web.Script.Services  Public Shared Function SaveUpVote(ByVal VoteID As Integer) As Boolean Dim test As Boolean = False Dim mySQL As New SQLHandler test = mySQL.UpdateVoteByID(VoteID) Return test End Function 

HTML:

  

为给定按钮投票时,使用ajax(对于aspx)调用server方法,如下所示:

  $(document).ready(function() { $("[id^=VoteMeUp]").click(function(event) { var dta = '{ "VoteId":' + $(event.target).val() + '}'; $.ajax( { type: 'POST', data: dta, url: 'Default.aspx/SaveUpVote', contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { $(event.target).text("Vote Casted"); }, error: function(x, y, z) { alert("Oops. An error occured. Vote not casted! Please try again later."); } } ); }); }); 

在Default.aspx.cs中

  [WebMethod] public static void SaveUpVote(int VoteId) { string UpdateSQL = "UPDATE TableName SET Votes = Votes + 1 WHERE PKID = @VoteId"; //do DB stuff return; } 

示例HTML:…

     

最简单的方法是使用WebMethods。

将EnablePageMethods设置为true,将ScriptManager添加到页面中

aspx页面:

  

将web方法属性分配给方法,该方法将(c#here)代码中的投票增加:

c#代码背后:

 [System.Web.Services.WebMethod] [System.Web.Script.Services.ScriptMethod] public string ChangeVote(string Arg){ ...logic to change votes } 

在您的javascript事件中,您可以通过pagemethods访问后面的代码,并定义函数以调用成功和失败案例:

JavaScript的:

 PageMethods.ChangeVote("sent item", OnChangeVoteComplete,OnChangeVoteFail); function OnChangeVoteComplete(arg){ //arg is the returned data } function OnChangeVoteFail(arg){ //do something if it failed } 

success函数接收WebMethod返回的数据。 您可以使用它来更新页面上的显示。

当使用点击UpVote按钮时,对执行查询的服务器进行ajax调用,再次使用数据库来增加投票。

      Vote UP     

并在服务器页面(myajaxsever.aspx)中,读取值并执行查询以增加投票列值。 qid的值是您可以从页面读取的问题ID,因为它将是动态的。