【问题标题】:Add info to txt file upon button click ASP.NET在按钮单击 ASP.NET 时将信息添加到 txt 文件
【发布时间】:2019-02-12 12:39:42
【问题描述】:

我想将一个 int 值(每次按下按钮时增加)存储到每个人的 .txt 文件中。

我不知道如何在单击时存储每个人的按钮值。这就是我想出的。在这方面需要帮助。

实际问题: 每个投票的人都应该能够看到总票数以及每个候选人的投票。您必须使用文件来记录投票。

@{

    var dataFile = Server.MapPath(@"~/App_Data/data.txt");

    string[] votesArr = File.ReadAllText(dataFile).Split(','); // your path
    string toWrite = "";

    for (int i = 0; i < votesArr.Length; 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);
}
<!DOCTYPE html>
<html>
<head>
    <title>Elections</title>
</head>
<body>
    <p id="1">Harry</p>
    <input id="1" type="submit" value="Vote Harry">

    <p id="2">John</p>
    <input id="2" type="submit" value="Vote John">

    <p id="3">May</p>
    <input id="3" type="submit" value="Vote May">

    <p id="4">Jane</p>
    <input id="4" type="submit" value="Vote Jane">
</body>
</html>

【问题讨论】:

标签: javascript jquery html asp.net


【解决方案1】:

例如,您可以使用文本格式。

哈利,0, 约翰,1, 5 月 2 日, 简,3

然后你可以用逗号分割,奇数是名字,一对是投票。

因此您可以使用奇数来查找候选人匹配,然后使用奇数+1 来获取选票值。你需要重写这个关于他的立场的新投票并再次写下这一行。

你需要寻找。

        string[] votesArr = File.ReadAllText("path").Split(','); // your path
        string toWrite = "";

        for (int i = 0; i < votesArr.Length -2; i += 2)
        {
            if (votesArr[i].Equals("May")) // Equals here is hardcoded, replace with parameter
                votesArr[i + 1] = "" + (Int32.Parse(votesArr[i + 1]) + 1);

            toWrite += votesArr[i] + votesArr[i+1];
        }


        File.WriteAllText("path", toWrite);

【讨论】:

  • 我重新编辑了我的帖子。你能帮我看看它是否在沿线的某个地方吗?
  • 如果您想检查该行是否为空,我认为您可以将其保存在字符串中并在进行拆分之前检查其长度。
  • 我做了一些改动。但是,当我编译时.. 它说 System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
  • 我更新了这一行 for(int i = 0; i &lt; votesArr.Length -2; i += 2) 这可能是 OutOfRangeException 的原因。如果你愿意,你可以分享你的代码以更好地检查它:)
猜你喜欢
  • 1970-01-01
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-15
  • 2019-04-21
  • 2019-06-24
  • 1970-01-01
相关资源
最近更新 更多