I'm trying to add control to the ASP.NET page. Controls are added successfully but can't access from code behind. In the sample below, when Button1 is clicked, there's no element in "uploads" (type HttpFileCollection).
Here's my mark-up:
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="add-remove-control.aspx.vb"
Inherits="APIU.Web.add_remove_control" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transi开发者_运维百科tional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="_Assets/scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var i = 1;
//allow only 3 elements
$('#add').click(function() {
if (i < 4) {
var add_input = '<input type="file" id="' + 'dynamic:' + i + '" name="' + 'dynamic:' + i + '" />'
var add_link = '<a href="#" class="remove">Remove</a>'
$('body').append('<p>' + add_input + add_link + '</p>');
i++;
}
});
$('.remove').live('click', function() {
$(this).parent('p').remove();
i--;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href="#" id="add">Add</a>
<asp:Button ID="Button1" runat="server" Text="Button" />
<br />
<p>
</p>
</div>
</form>
</body>
</html>
Code behind:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim uploads As HttpFileCollection
uploads = HttpContext.Current.Request.Files
Dim sfile As String
For i As Integer = 0 To (uploads.Count - 1)
If (uploads(i).ContentLength > 0) Then
Dim c As String = System.IO.Path.GetFileName(uploads(i).FileName)
Try
uploads(i).SaveAs("C:\UploadedUserFiles\" + c)
sfile += uploads(i).FileName & "<br/>"
Catch Exp As Exception
End Try
End If
Next i
End Sub
Why there's no element in "uploads" (type HttpFileCollection)?
The reason it doesn't show up server-side is here:
$('body').append('<p>' + add_input + add_link + '</p>');
This appends to the <body>
element, which is most importantly outside the <form>
...so the inputs you're using aren't included in the POST. Append the elements to the <form>
instead, like this:
$('form').append('<p>' + add_input + add_link + '</p>');
This is the same reason input elements inside a .dialog()
call don't get submitted in ASP.Net, again it's moved just before </body>
and outside the </form>
...you need a .dialog().parent().appendTo('form')
for the same reason there.
精彩评论