简体   繁体   中英

How to increment value whenever same button is clicked?

I would like int countHarry to keep incrementing by 1 whenever user clicks on "Vote Harry" button. The output will be written inside "data.txt". However, my data.txt will only show value as 1. Need advise. Thanks.

This is a .cshtml file.

Current output: Harry, 1 Expected output: Harry, 3 (where int value increases upon click each time)

 @{ var result = ""; int countJohn = 1; int countHarry = 1; if (IsPost) { var dataFile = Server.MapPath(@"~/App_Data/data.txt"); if (Request["submit"] == "Vote Harry") { //var harry = Request["Harry"]; var userData = "Harry" + "," + countHarry + Environment.NewLine; File.AppendAllText(@dataFile, userData); // countHarry += countHarry; does not increases the count inside .txt at all result = "Information saved."; } else if (Request["submit"] == "Vote John") { //var john = Request["John"]; var userData = "John" + "," + (Int32.Parse("1")) + Environment.NewLine; File.AppendAllText(@dataFile, userData); result = "Information saved."; countJohn += 1; } } } 
 <!DOCTYPE html> <html> <head> <title>Elections</title> </head> <body> <form id="form1" method="post"> <div> <table> <tr> <td>Harry</td> <td><input id="Harry" name="submit" type="submit" value="Vote Harry"/></td> </tr> <tr> <td>John</td> <td><input id="John" name="submit" type="submit" value="Vote John" /></td> </tr> <tr> <td>Bryan</td> <td><input id="Bryan" name="submit" type="submit" value="Vote Bryan" /></td> </tr> <tr> <td>Jack</td> <td><input id="Jack" name="submit" type="submit" value="Vote Jack" /></td> </tr> </table> </div> <div> @if (result != "") { <p>Result: @result</p> } </div> </form> </body> </html> 

I guess you just need to define countHarry here:

@{
var result = "";
int countJohn = 1;
int countharry = 1;

Now you can reach countharry where you need because it's "global"..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM