【发布时间】:2019-06-05 14:16:09
【问题描述】:
我想在单击按钮时使用System.IO 创建一个简单文件。我的代码实际上会生成该文件,但它会在每次浏览器重新加载时创建该文件,而不是仅在单击按钮时生成该文件。下面是我的代码。谁能帮忙看看他们是否能弄清楚为什么会在页面加载时触发?
using System;
using System.IO;
namespace ColorPicker
{
public partial class ColorPicker : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Empty for now
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
SetEventHandlers();
}
private void GenerateSassFile()
{
var ColorInputVal = ColorInput;
ColorInputVal.Attributes.Add("class", "form-control");
ColorInputVal.Attributes.Add("value", "#000");
var ColorInputH = this.ColorInputH.Value = "red";
var RenderStyleBtn = RenderStyle;
RenderStyleBtn.Text = "Render!";
string path = @"c:\ColorPicker\Scss\_vars.scss";
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("$primary: " + ColorInputH + " !important;");
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s;
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
private void RenderButton_Click(object sender, EventArgs e)
{
GenerateSassFile();
System.Diagnostics.Debug.WriteLine("Button clicked");
}
private void SetEventHandlers()
{
RenderStyle.Click += RenderButton_Click;
}
}
}
【问题讨论】:
-
您是否在浏览器重新加载再次传输帖子数据?如果 postdata 包含视图状态,它具有启动该帖子所发生的最终事件的信息,超过发布的表单中包含的数据......因此,如果您在 Renderstyle 单击后重新传输该信息,页面类将重新访问视图状态信息并再次找到RenderStyle 按钮的点击事件,再次启动点击委托
-
不要手动分配事件处理程序。对于您的按钮,使用 ASPX 标记来分配处理程序。
标签: c# asp.net .net system.io.file