我想创建一个带有ASP.NET FileUpload Control和一些Textboxes和一个提交按钮的C#WebForm。想法:用户选择文件,输入一些数据,提交表格检查数据,如果有效,则将文件保存在服务器上,否则显示错误信息。有很多关于UpdatePanel触发器等的帖子,但不是一个有效的解决方案。
这里是我的代码:
protected void Page_Load(object sender, EventArgs e) {
// for FileUpload-Control outside UpdatePanel
Page.Form.Attributes.Add("enctype", "multipart/form-data");
}
protected void Button1_Click(object sender, EventArgs e) {
bool valid = true;
string errorMessage = DateTime.Now.ToLongTimeString() + ": ";
if (this.TextBox1.Text.Equals("")) {
valid = false;
errorMessage += "Missing Textbox1<br/>";
}
if (this.TextBox2.Text.Equals("")) {
valid = false;
errorMessage += "Missing Textbox2<br/>";
}
if (this.TextBox3.Text.Equals("")) {
valid = false;
errorMessage += "Missing Textbox3<br/>";
}
if (!this.FileUpload3.HasFile) {
// is alway false!
errorMessage += "Missing FileUpload3<br/>";
}
if (valid) {
// never fires, because .HasFile is always false
this.Label1.Text = "valid!";
// do upload stuff
this.FileUpload3.SaveAs("foobar");
} else {
this.Label1.Text = errorMessage;
}
}
这是我的样本ASPX:
<form id="Upload" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:FileUpload ID="FileUpload3" runat="server" />
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</form>
有没有人看到,为什么我的FileUpload总是空的,虽然它在UpdatePanel之外并且我在Page_Load()事件中有所需的行?如果,你能调整代码吗?
谢谢 的SiS
答案 0 :(得分:0)
<form id="Upload" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:FileUpload ID="FileUpload3" runat="server" />
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>