【发布时间】:2019-07-06 21:16:39
【问题描述】:
我在下面创建了一个数组来存储所需的信息。
我的预期输出应该是smth,例如:
约翰,2
5 月 3 日
每当用户按下特定按钮 id 时,名称旁边的值都应该递增并替换旧值本身。
不确定为什么没有将信息写入data.txt 文件。
请指教。谢谢。
@{
var result = "";
if (IsPost)
{
char[] delimiterChar = { ',' };
var dataFile = Server.MapPath(@"~/App_Data/data.txt");
string[] votesArr = File.ReadAllLines(dataFile);
if (votesArr == null)
{
// Empty file.
result = "The file is empty.";
}
string toWrite = "";
for (int i = 0; i < votesArr.Length - 2; i += 2)
{
if (votesArr[i].Equals("Harry")) // Equals here is hardcoded, replace with parameter
{
votesArr[i + 1] = "" + (Int32.Parse(votesArr[i + 1]) + 1);
}
else if (votesArr[i].Equals("John")) // Equals here is hardcoded, replace with parameter
{
votesArr[i + 1] = "" + (Int32.Parse(votesArr[i + 1]) + 1);
}
else if (votesArr[i].Equals("May")) // Equals here is hardcoded, replace with parameter
{
votesArr[i + 1] = "" + (Int32.Parse(votesArr[i + 1]) + 1);
}
else if (votesArr[i].Equals("Jane")) // Equals here is hardcoded, replace with parameter
{
votesArr[i + 1] = "" + (Int32.Parse(votesArr[i + 1]) + 1);
}
toWrite += votesArr[i] + votesArr[i + 1];
}
File.WriteAllText(dataFile, toWrite);
result = "Information is saved.";
}
}
<!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>
【问题讨论】:
-
您确实应该从小型控制台应用程序开始整理更新文件的代码...然后切换到处理 Web 提交...这样做将帮助您查看从文件中读取的内容(因为由于某种原因您无法搜索“C# read CSV”)并写入文件(这与您此时正在阅读的内容非常不同)。
标签: javascript c# html arrays