ASP.NET using Button instead of FileUpload to upload files - asp.net

I'm trying to upload a file with Button element using hidden FileUpload element with ASP.NET using this snippet:
protected void Page_Load(object sender, EventArgs e)
{
Button2.Attributes.Add("onclick", "document.getElementById('" + FileUpload1.ClientID + "').click();");
}
My Button has Id = "Button2", FileUpload Id = "FileUpload1". Clicking on the button Windows Explorer opens successfully to upload files but FileUpload.HasFile still returns false in further code (no file gets loaded even though explorer gets opened and file is selected).
What is the cause of this problem and how to fix it?

Well, I suppose you want to hide the the FileUpload Control and still be able to upload the files.
Follow the following steps to achieve the required:
Place a FileUpload Control with the class hidden. Like below:
<style>
.hidden{
display: none;
}
</style>
<asp:FileUpload runat="server" ID="FileUpload1" CssClass="hidden" />
Then place a Button that will be visible to client and will handle the Javascript events
<asp:Button runat="server" ID="Button1" Text="Upload File" OnClick="Button1_Clicked" />
Add the Javascript events to handle things
$(document).ready(function(){
// This event will help click the FileUpload control
$('#<%= Button1.ClientID %>').on('click', function(){
$('#<%= FileUpload1.ClientID %>').click();
return false; // important to return false, so it does not posts back yet.
});
$('#<%= FileUpload1.ClientID %>').on('change', function(){ // To see if the file selection was changed and the user has selected something
if($(this).val() == ''){
alert('No file selected');
return false;
}
if(confirm('Do you want to upload this file? ' + $(this).val())){
__doPostBack('<%= Button1.ClientID %>', ''); // this will postback to the server click event
}
});
});
Now, handle the uploaded file.
public void Button1_Clicked(object sender, EventArgs e)
{
// Handle your upload function
var hasFile = FileUpload1.HasFile;
}
PS: It was a rough Idea, the code is not tested so it might need some love.

Related

I need to open dialog box on linkbutton click using asp.net

Hi i need to display dialog box on linkbutton click in asp.net.On this dialog there will be file upload control to browse files.
Can you please suggest me any example.Because i am pretty new in development.
Ok, The way you must do is :
1) create a page that has a File Upload control inside it (name it for exmaple MyDialogPage.aspx)
and in code behind
protected void btn1_click(object sender, EventArgs e)
{
//do ur stuff with file
}
2) on the Calling page do this:
<asp:LinkButton Id="callDiag" runat="server" onClientClick="CalljavascriptFunction();return false"/>
3) write this javascript function on the Calling page:
<script>
function CalljavascriptFunction()
{
var url="MyDialogPage.aspx";
var retval = window.showModalDialog(url, window, "center:yes;dialogWidth:800px;dialogHeight:600px");
}
</script>
regards

ASP OnText event based controlling button control

What I'm trying to do is has a specific button enables or disables based on the number of characters that have been imputed into a textbox.
The event only fire when I click off the textbox, maybe i'm looking for something else?
<telerik:RadTextBox ID="InputVinInformationTextBox" runat="server"
Skin="Office2010Blue"
Width="250px"
MaxLength="16"
OnTextChanged="InputVinInformationTextBox_OnText"
AutoPostBack="true">
</telerik:RadTextBox>
protected void InputVinInformationTextBox_OnText(object sender, EventArgs e)
{
if (InputVinInformationTextBox.Text.Length >= 8)
{
VinSubmitButton.Enabled = true;
}
else
{
VinSubmitButton.Enabled = false;
}
}
If you don't mind using jQuery you could remove the OnTextChanged function and instead bind the functionality to the keyup event. All you need to do is to add the following in your <head> tag:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$("#<%=InputVinInformationTextBox.ClientID%>").keyup(function() {
if (InputVinInformationTextBox.Text.Length >= 8)
{
VinSubmitButton.Enabled = true;
}
else
{
VinSubmitButton.Enabled = false;
}
}
});
</script>
I'm not sure what your VinSubmitButton is, but I assume, since it was working in your example, that that is an element that you already have stored.
This behavior is by design:
All RadInput controls provide the TextChanged server event, which is
raised when the AutoPostBack property is set to true, the user types
valid entry, and the input loses focus.
The TextChanged event only occurs if the value of the input control
actually changes. If the user changes the string in the input control
but does not actually change the value...the TextChanged event does
not occur.
See this help topic on Telerik's site for more info.
I recommend using the OnTextChanged event as you have been, as it will only fire when valid text is entered that changes the previous value of the RadTextBox.
Alternatively, you can use JavaScript to determine when an appropriateĀ number of characters have been entered, then trigger the request manually.
<telerik:RadTextBox ID="InputVinInformationTextBox" runat="server"
Skin="Office2010Blue"
Width="250px"
MaxLength="16"
OnLoad="InputVinInformationTextBox_OnLoad">
<ClientEvents OnKeyPress="InputVinInformationTextBox_OnKeyPress" />
</telerik:RadTextBox>
<script type="text/javascript">
function InputVinInformationTextBox_OnKeyPress(sender, args) {
var text = sender.get_value();
if (text.length >= 8) {
var ajaxManager = $find('<%= RadAjaxManager.GetCurrent(Page) %>');
ajaxManager.ajaxRequestWithTarget(sender.get_id(), '');
}
}
</script>
The code above assumes you are also using a RadAjaxManager on the page and that it has been configured to update all/part of the page when triggered by the RadTextBox. You'd need to check the RadTextBox value during the OnLoad event of the control (or later) so that all ViewState and form values have been initialized for the control.
protected void InputVinInformationTextBox_OnLoad(object sender, EventArgs e)
{
if (InputVinInformationTextBox.Text.Length >= 8)
{
VinSubmitButton.Enabled = true;
}
else
{
VinSubmitButton.Enabled = false;
}
}

Clearing the value of ASP.Net 2.0 File Upload Control using javascript that works on all browser?

We are running following javascript function:
function btn_AddToList_Click() {
var filePath = document.getElementById("FileUpload").value;
if(filePath.length > 0)
{
var opt = new Option(filePath,filePath);
var listBox = document.getElementById("ListBox");
listBox.options[listBox.options.length] = opt;
}
}
Function binding:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btn_AddToList.Attributes.Add("onclick", "btn_AddToList_Click(); return false;");
}
}
HTML:
asp:FileUpload ID="FileUpload" runat="server" Width="394px"
asp:ListBox ID="ListBox" runat="server" Width="394px"
asp:Button ID="btn_AddToList" runat="server" Enabled="true" Text="Add"
Issue is that value of "FileUpload" is not get cleared after we click "Add" button. Any help?
You can not set/clear the value of FileUpload control programmatically. That is a restriction for a security reason. Consider this if this restriction was not there, you could set the value of FileUpload control to some arbitrary file and upload it to your server. You won't be able to achieve this in current shape.
As a work around you can try to bring another textbox exactly on top of textbox part of FileUpload control. This way you will be give the same feeling what you are trying to achieve. But that is also not ideal and may not work properly.

window.location.href not working in Safari when using onkeypress

I'm using an asp textbox and a search button. In Safari if I click the search button i get redirected to the search results page using javascript window.location.href. But strangely the same javascript will not redirect to the page if I press return in the textbox.
Using the alert function I can see that window.location.href has the the correct url and the location bar at the top changes from the search page(default.aspx) to the search results url however when I click OK to the alert box the url at the top reverts back to the default.aspx page. It works on ie7/8/firefox/chrome but not safari. Here is my javascript,cs and aspx code:
function submitSearchOnEnter(e) {
var CodeForEnter = 13;
var codeEnteredByUser;
if (!e) var e = window.event;
if (e.keyCode) codeEnteredByUser = e.keyCode;
else if (e.which) codeEnteredByUser = e.which;
if (codeEnteredByUser == CodeForEnter)
RedirectToSearchPage();
}
function RedirectToSearchPage() {
var searchText = $get('<%=txtHeaderSearch.ClientID%>').value
if (searchText.length) {
window.location.href = "Search.aspx?searchString=" + searchText;
}
}
protected void Page_Load(object sender, EventArgs e)
{
txtHeaderSearch.Attributes.Add("onkeypress", "submitSearchOnEnter(event)");
}
<asp:Panel ID="pnlSearch" runat="server" DefaultButton="lnkSearch">
<asp:TextBox ID="txtHeaderSearch" runat="server" CssClass="searchBox"></asp:TextBox>
<asp:LinkButton ID="lnkSearch" OnClientClick="RedirectToSearchPage(); return false;"
CausesValidation="false" runat="server" CssClass="searchButton">
SEARCH
</asp:LinkButton>
</asp:Panel>
I've tried return false; which doesn't allow me to enter any characters in the search box. I've spent ages online trying to find a solution. Maybe it has something to do with setTimeout or setTimeInterval but it didn't work unless i did it wrong.
In Safari, the 'onkeypress' event is only fired if the key press results in a character being added to an HTML element. I'm not sure that this will fire at all when you press Enter in a one-line text box. See a partial explanation of this behavior here.
As Tim Down says, you probably want onkeydown instead.
Use keydown instead of keypress and you should be fine.
protected void Page_Load(object sender, EventArgs e)
{
txtHeaderSearch.Attributes.Add("onkeydown", "submitSearchOnEnter(event)");
}
I had a similar issue.
It worked for me when using onKeyUp:
function bodyOnKeyUp(event)
{
if (!event) {event=window.event;}
var Esc = 27;
switch (event.keyCode) {
case Esc:
document.location.href='URL';
break;
}
}
<body onKeyUp="bodyOnKeyUp(event)">
...
</body>

ASP.NET WebForms + Postback then open popup

I have a LinkButton that has to postback to perform some logic.
Once it is finished, instead of loading the page back up in the browser, I want to leave it alone and pop open a new window.
So far, the best idea I've had is to put the LinkButton in an UpdatePanel, and have it render some JavaScript out when it reloads, yet I think that is totally hacky. Also, if I recall right, JavaScript within a update panel won't run anyways.
Any other ideas?
Use LinkButton.PostBackUrl to set a different page to POST to, and some client script to get a new window (and the old target restored so that future postbacks work normally). The 2nd page can use PreviousPage to get access to any needed state from the original page.
<script runat="server">
void lnk_Click(object sender, EventArgs e) {
// Do work
}
</script>
<script type="text/javascript">
var oldTarget, oldAction;
function newWindowClick(target) {
var form = document.forms[0];
oldTarget = form.target;
oldAction = form.action;
form.target = target;
window.setTimeout(
"document.forms[0].target=oldTarget;"
+ "document.forms[0].action=oldAction;",
200
);
}
</script>
<asp:LinkButton runat="server" PostBackUrl="Details.aspx" Text="Click Me"
OnClick="lnk_Click"
OnClientClick="newWindowClick('details');" />
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
// Do some server side work
string script = "window.open('http://www.yahoo.com','Yahoo')";
if (!ClientScript.IsClientScriptBlockRegistered("NewWindow"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(),"NewWindow",script, true);
}
}
One thing you could try is to have your LinkButton OnClick event do its processing, then register a Page.ClientScript.RegisterStartupScript with the popup code, which will put some Javascript into the tag to fire off after the page loads. This should launch your new window after the processing completes.
EDIT: Reading your comment, I believe you can still use this approach, have your results stored in a session variable, and then have the popup page pull the results from there.

Resources