使用Asp.Net控件启动jQuery方法

使用Asp.Net控件启动jQuery方法,jquery,asp.net,verification,Jquery,Asp.net,Verification,当我从Asp.Net中的FileUpload控件中选择一个文件时,我尝试启动jQuery方法,但它不起作用。jQuery方法必须检查所选的文件大小。我怎样才能解决这个问题 <script type="text/javascript"> function ValidateUploadButton() { //this code will be executed when a new file is selected $('#FileUpload1

当我从Asp.Net中的FileUpload控件中选择一个文件时,我尝试启动jQuery方法,但它不起作用。jQuery方法必须检查所选的文件大小。我怎样才能解决这个问题

<script type="text/javascript">
    function ValidateUploadButton() {
        //this code will be executed when a new file is selected
        $('#FileUpload1').bind('change', function () {
            //converts the file size from bytes to MB 
            var fileSize = this.files[0].size / 1024;

            //checks whether the file is less than 1 MB 
            if (fileSize > 1) {
                $('#errorMessage').html("The file is too big")
                alert("okey");
                //successfully validated 
            }
            else {
                alert("else");
            }
        });
    }
</script>

我已将ClientValidationFunction属性更改为onchange

<asp:FileUpload ID="FileUpload1" runat="server" onchange="ValidateUploadButton();" />
<span id="errorMessage"></span>
编辑脚本以删除“更改”绑定,因为现在ValidateUploadButton因更改而被调用

<script type="text/javascript">
function ValidateUploadButton()
{
    //this code will be executed when a new file is selected
    //converts the file size from bytes to Ko 
    var fileSize = $('#FileUpload1')[0].files[0].size / 1024 / 1024;
    // USE THIS BELOW IF THE ONE ABOVE DOESN'T WORK
    //var fileSize = $('#<%= FileUpload1.ClientID %>')[0].files[0].size / 1024 / 1024;

    //checks whether the file is less than 1 MB 
    if (fileSize > 1)
    {
        $('#errorMessage').html("The file is too big")
        alert("okey");
        //successfully validated 
    }
    else
    {
        alert("else");
    }
}
</script>
编辑

对不起,我没有彻底测试这个。现在应该可以了。正确引用文件大小的javascript语法是错误的。此外,我还增加了1024的额外除法,因此您将以MB而不是KB获得它


注意-这只适用于一个文件,不支持多个文件。

@HQtunes.com是的,我在发布之前没有测试它。它现在对我有效,所以希望它对你有效。还要注意注释掉的fileSize变量。因为您的fileupload是runat=server,我认为有时实际的引用ID会因为内容母版页而发生更改,因此您可能需要像注释掉的行中那样以不同的方式获取其ID。
<script type="text/javascript">
function ValidateUploadButton()
{
    //this code will be executed when a new file is selected
    //converts the file size from bytes to Ko 
    var fileSize = $('#FileUpload1')[0].files[0].size / 1024 / 1024;
    // USE THIS BELOW IF THE ONE ABOVE DOESN'T WORK
    //var fileSize = $('#<%= FileUpload1.ClientID %>')[0].files[0].size / 1024 / 1024;

    //checks whether the file is less than 1 MB 
    if (fileSize > 1)
    {
        $('#errorMessage').html("The file is too big")
        alert("okey");
        //successfully validated 
    }
    else
    {
        alert("else");
    }
}
</script>