How To Update Votes Client Side Using Webforms
Solution 1:
When a vote is cast for a given button, call the server method using ajax (for aspx) as follows:
$(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.");
}
}
);
});
});
In Default.aspx.cs
[WebMethod]
publicstaticvoidSaveUpVote(int VoteId)
{
string UpdateSQL = "UPDATE TableName SET Votes = Votes + 1 WHERE PKID = @VoteId";
//do DB stuffreturn;
}
Sample HTML: ...
<body><buttonid="VoteMeUp1"value="817">1 - Vote for this</button><buttonid="VoteMeUp2"value="818">2 - Vote for that</button></body>
...
Solution 2:
the easiest method to do this would be WebMethods.
Add a ScriptManager to your page with EnablePageMethods set to true
aspx page:
<asp:ScriptManagerID="ScriptManager1"runat="server"EnablePageMethods="true" />
Assign a web method attribute to the method which increments the votes in your (c# here) code behind:
c# code behind:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
publicstringChangeVote(string Arg){
...logic to change votes
}
in your javascript event, you can then access the code behind via pagemethods, and define functions to call on success and fail cases:
javascript:
PageMethods.ChangeVote("sent item", OnChangeVoteComplete,OnChangeVoteFail);
functionOnChangeVoteComplete(arg){
//arg is the returned data
}
functionOnChangeVoteFail(arg){
//do something if it failed
}
the success function receives the data returned by the WebMethod. You can use this to update the display on the page.
Solution 3:
When use clicks on the UpVote button, make an ajax call to the server where you execute a query againist the database to increment the vote.
<html><head><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script></head><body><ahref="#"id="aUpVote">Vote UP </a></body><scripttype="text/javascript">
$(function(){
$("#aUpVote").click(function(){
$.post("myajaxserverpage.aspx?qid=12",function(data){
alert(data);
});
});
});
</script></head>
and in the server page (myajaxsever.aspx), read the values and execute your query to increment the Vote column value. value of qid is the question id this you can read from the page because it is going to be dynamic.
Post a Comment for "How To Update Votes Client Side Using Webforms"