簡體   English   中英

每當單擊同一按鈕時如何增加值?

[英]How to increment value whenever same button is clicked?

我希望每當用戶單擊“ Vote Harry”按鈕時,int countHarry都將遞增1。 輸出將被寫入“ data.txt”中。 但是,我的data.txt僅將值顯示為1。 謝謝。

這是一個.cshtml文件。

當前輸出:Harry,1預期輸出:Harry,3(每次單擊時,int值都會增加)

 @{ 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> 

我想您只需要在此處定義countHarry:

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

現在,您可以在任何需要的地方進行購物,因為它是“全球性的”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM