2011-11-09 57 views
0

我看到了这个问题,"Show Open Dialog on a Button click"jQuery的文件上传清爽页面

“我必须显示在点击一个按钮一个打开的对话框。基本上我有上传文件,为此我使用FileUpload控件,但我不想把它展示给用户,而不是我要显示一个按钮”

而答案是:

<script type="text/javascript">  
    $(document).ready(function() {  
     $("#btn").click(function() {  
     $("#FileUpload1").click();   
     return false; 
     });   
    }); 
    </script> 
    <style type="text/css">  
     .Class { visibility:hidden;}  
    </style> </head> <body>  
    <form id="form1" runat="server"> 
    <div>  
     <asp:Button ID="btn" runat="server" Text="Send File"/> 
     <asp:FileUpload ID="FileUpload1" CssClass="Class" runat="server" /> 

但我试过了,它所做的只是刷新页面,任何人都知道问题是什么?

+2

当然,您可以想出更具描述性的标题。 –

+0

你能发布生成的HTML吗? – Blender

+0

@Matt - 你对一个叫“班级”的人有什么期望?只是在开玩笑;-) –

回答

1

因为“FileUpload1”不是ClientID。只要看看你的页面生成的HTML源代码,你会看到。

你应该使用类似:

<script type="text/javascript">  
$(document).ready(function() {  
    $("#<%= btn.ClientID %>").click(function() {  
    $("#<%= FileUpload1.ClientID %>").click();   
     return false; 
    });   
}); 
</script> 
+0

@多米尼克它不工作 –

+0

我刚刚尝试了他的代码,它完美的作品。执行此操作..打开页面。单击发送文件按钮。按Ctrl + Shift + J,查看列出了哪些错误。 –

+0

我想它毕竟是在工作! –

0

所有的服务器端控件(那些runat="server"属性)有自己的ID通过ASP.NET重新写入。您的ID实际上看起来像ctl00_MainContent_btn

您可以通过使用<%= btn.ClientID %>服务器标签或通过为您的控件分配CSS类并在JavaScript/jQuery中引用该类来解决此问题。

编辑:你可能还需要确保你的ASP按钮不是一个提交按钮,这将导致生成的页面提交表单。

+0

它不起作用 –

+0

@RoyGavrielov,**什么**不工作?我们需要更多的信息来帮助你解决你的问题。 – jwiscarson

+0

对不起,我换了(“#btn”)和(“<%= btn。(“#<%= FileUpload1.ClientID%>”)并且仍然不起作用 –

0

这听起来像是一个安全风险,如果安全阻止了它的工作,我不会感到惊讶。

看看这个jQuery Ajax Upload插件。

+0

@ James我可以' t在我的组织中使用 –

+0

你不能使用什么?一个jQuery脚本? –

+0

安装一个插件 –

0

我会建议你不要去那条路线。如果你想避免向用户显示FileUpload控制.. use this

+0

@ mohib我不能在我的组织中使用它 –

0

使客户端模式的静态能够访问你喜欢这个

<asp:FileUpload ID="FileUpload1" ClientIDMode="Static" CssClass="Class" runat="server" /> 
    <asp:Button ID="btn" ClientIDMode="Static" runat="server" Text="Send File"/> 
0

你的页面刷新,因为表单的目标是隐含在当前页面控件。您需要将表单的目标设置为(例如)隐藏的iframe:

<form id="my-form" action="url" target="form-target" method="post"> 
    <!-- your form here --> 
</form> 

<iframe id="form-target" name="form-target" style="display:none;"></iframe> 

<script> 
    // Assuming you are using jquery 
    var form = $('#my-form'), 
     iframe = $('#form-target'); 

    // create a function to be called each time the iframe loads 
    iframe.load(function() { 
    var responseText, iframeBody; 

    // Get the response from the server. It will be in the body tag of your iframe 
    iframeBody = $(this).contents().find('body'); 
    responseText = iframeBody.text().trim(); 
    // Don't continue until we actually have a response 
    if (!responseText) return; 
    // Clear the iframe's html so this function won't be called again for the same content 
    iframeBody.html(''); 

    // do whatever you want with the response, for example JSON decode it 
    response = JSON.parse(responseText); 
    }); 
</script>