关于在UpdatePanel里使用FileUpload控件

发布时间:2013-09-19 11:33:46来源:阅读(4040)

    遇到这个问题就在网上找解决方案,现在找到的方法贴出来,本人没测试,可用不可用不便评论,有需要的朋友试下吧,别忘了告我结果哦,呵呵

    方法一:

    曾在开发ATLAS时候,想用UpdatePanel (UP)来上传文件,但是没有想到FileUpload (FU)控件不能在UP里使用,这里有个小技巧,可以让你的FU控件在UP里面起做用. 来看代码:

    HTML:     


            
            
            
                
                                        Text="Upload" />
                

            
       
             
            


    CODE BEHIND:
        Protected Sub Page_Load()Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

            Me.cmdButton1.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(Me.cmdButton2, ""))

        End Sub

        Protected Sub cmdButton2_Click()Sub cmdButton2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            If Me.FileUpload1.HasFile Then
                System.Threading.Thread.Sleep(1000)
                Me.Label1.Text = Me.FileUpload1.FileName
            End If
        End Sub



    这样的话,当你在点击UP里面的UPLOAD按钮时,整个页面就会回传,当然你的可以找到你FU控件里面的文件,所以上传文件是没问题. OK~

    后来考虑到界面问题,想把button2按钮给隐藏掉,然后设置button2的visible的属性为false.运行是却出现了如下的错误:
    回发或回调参数无效。在配置中使用 或在页面中使用 <%@ Page EnableEventValidation="true" %> 启用了事件验证。出于安全目的,此功能验证回发或回调事件的参数是否来源于最初呈现这些事件的服务器控件。如果数据有效并且是预期的,则使用 ClientScriptManager.RegisterForEventValidation 方法来注册回发或回调数据以进行验证。
    把button2的visible的属性重新该为true,问题就不在重新出现,现在对此不能理解
    麻烦知道的朋友告诉一声.谢谢!!!

    方法二:

    发现把FileUpload控件放到ASP.NET AJAX UpdatePanl中,事件倒是能捕捉到,但FileUpload在后台的HasFile老是为False,也就是说文件根本没传到服务端,用Google查了查,发现ASP.NET AJAX官方文档已经说明了FileUpload和AJAX不兼容!

    郁闷经过实验还是有办法的:
    protected void DatePicker1_SelectionChanged(object sender, EventArgs e)
    {
        Label1.Text = DatePicker1.DateValue.ToShortDateString();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {       
        if (FileUpload1.HasFile)
        {
             Label1.Text = FileUpload1.FileName;
        }
    }

    It is at this point that we experience the problem. Run the form and you will find that the file upload control does not work. Because the file upload control is within an update panel the file is not posted to the server. 

    3. Enable File Upload Full Postback

    As mentioned earlier the trick is to force the file upload control to perform a full postback, and we do this using triggers. Triggers allow the developer to specify what will cause partial and full postbacks. They must be defined within the UpdatePanel but outside of the ContentTemplate. We want to create a trigger that will instruct the button that we are using for the upload to perform a full postback. The updated markup is: 

    Text="Upload" OnClick="Button1_Click" />


    Now when the form is run the DatePicker is still working asynchronously, but the file upload is also working, thanks to the PostBackTrigger