我希望int countHarry每当用户单击“ Vote Harry”按钮时都将递增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>
答案 0 :(得分:0)
我想您只需要在此处定义countHarry:
@{
var result = "";
int countJohn = 1;
int countharry = 1;
现在,由于它是“全局”的,因此您可以在需要的地方到达杂货铺。