File uploading in update panel still refreshing - c#

I search over internet to use upload file in update panel.
I want to avoid page refreshing when i click on file upload.
So i put my codes in update panel with a trigger
but still refreshing ...
Codes :
<asp:ScriptManager runat="server" ID="ScriptManager1" EnablePartialRendering="true"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional" ChildrenAsTriggers="true">
<Triggers>
<asp:PostBackTrigger ControlID="imageUploadAction" />
</Triggers>
<ContentTemplate>
<div class="fileUpload btn btn-primary btn-block btn-lg">
<span>آپلود</span>
<asp:FileUpload CssClass="inputfile" runat="server" ID="imageUpload" />
</div>
<br />
<div class="alert alert-info" runat="server" id="imageAlert"></div>
<div style="border-bottom: 1px solid #ddd;"></div>
<br />
<asp:Button runat="server" ID="imageUploadAction" CssClass="btn btn-block btn-lg btn-success" Text="ارسال" OnClick="imageUploadAction_Click" />
</ContentTemplate>
</asp:UpdatePanel>
Behind Code :
protected void imageUploadAction_Click(object sender, EventArgs e)
{
Debug.WriteLine("Uploading" + " " + imageUpload.HasFile);
Boolean fileOK = false;
String path = Server.MapPath("~/Assets/image/posts/");
if (imageUpload.HasFile)
{
String fileExtension = System.IO.Path.GetExtension(imageUpload.FileName).ToLower();
String[] allowedExtensions = { ".jpg", ".png" };
for (int i = 0; i < allowedExtensions.Length; i++)
if (fileExtension == allowedExtensions[i])
fileOK = true;
}
if (fileOK)
{
try
{
int last = getLastImage() + 1;
string link = path + last + ".jpg";
imageUpload.PostedFile.SaveAs(link);
db.insertPhoto(link);
imageAlert.InnerText = "فایل آپلود شده است ، کد عکس : " + last;
}
catch (Exception ex)
{
ExceptionUtility.LogExceptionNotFailure(ex);
Debug.WriteLine(ex.ToString());
imageAlert.InnerText = "فایل نمیتواند آپلود شود.";
}
}
else
{
imageAlert.InnerText = "فایل مجاز نیست";
}
}

You're setting up the imageUploadAction button to be a PostBackTrigger (thus not async) which causes a full reload of the page.
Note that there is no way to use a regular uploader using an UpdatePanel. If you really want asynchronous file upload, you'll have to implement quite a bit of code both on the client and the server side.
Take a look at FlowJs here
https://github.com/flowjs/flow.js
with a demo here
http://flowjs.github.io/ng-flow/
Hope that helps

Related

C# ASP.NET - Not able to hide image in updateprogress after response redirect

I have one Ajax UpdateProgress for only one UpdatePanels in the page.
The updatepanel has a gridview with a download button.
Once user clicks on the button, the 'wait' Image shows up, but keeps showing even after the download is complete.
How should I hide it, once the download is done.
My code below but not working, because the image is showing even after the download is complete.
.cs
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton ImageButton1 = (ImageButton)sender;
sIDint = ImageButton1.CommandArgument.ToString();
Thread.Sleep(3000);
HttpCookie cookie = new HttpCookie("ExcelDownloadFlag")
{
Value = "Flag",
Expires = DateTime.Now.AddDays(1)
};
Response.AppendCookie(cookie);
Response.Redirect("pdf.aspx?sID=" + sIDint.ToString());
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "HideImage();", true);
ImageButton imgLike = (ImageButton)FindControl("imgLike");
if (imgLike != null)
{
imgLike.Visible = false;
}
}
.aspx
function HideImage() {
$(#imgLike).hide();
}
<asp:TemplateField HeaderText="Dwn">
<ItemTemplate>
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<div class="modal">
<div class="center">
<img alt="" src="/Img/ajax-loader.gif" id="imgLike" />
</div>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ImageButton1" />
</Triggers>
<ContentTemplate>
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="/img/download.gif"
OnClick="ImageButton1_Click"
CommandArgument='<%# Eval("ID") %>' />
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
Edit
Solved using
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton ImageButton1 = (ImageButton)sender;
string sIDint = ImageButton1.CommandArgument.ToString();
Thread.Sleep(3000);
HttpCookie cookie = new HttpCookie("ExcelDownloadFlag")
{
Value = "Flag",
Expires = DateTime.Now.AddDays(1)
};
Response.AppendCookie(cookie);
ScriptManager.RegisterStartupScript(this, typeof(string), "OpenWindow", "window.open('pdf.aspx?sID=" + sIDint + "');", true);
}

File is getting saved when uploaded 2nd time

<div class="PriceCalculatorForm">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Panel ID="PnlSaveData" runat="server">
<div class="form-group">
<div class="col-md-1"></div>
<label class="control-label col-sm-4">Upload Image</label>
<div class="col-sm-4">
<asp:FileUpload ID="ImageFileUploader" runat="server" />
<asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
</div>
<div class="col-md-2">
<asp:Button ID="btnImageUpload" runat="server" Text="Upload Image" OnClick="btnImageUpload_Click" CssClass="btnSearch" />
</div>
<div class="col-md-1"></div>
</div>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnImageUpload" />
</Triggers>
</asp:UpdatePanel>
</div>
protected void btnImageUpload_Click(object sender, EventArgs e)
{
if (ImageFileUploader.HasFile)
{
string FileExtension = Path.GetExtension(ImageFileUploader.FileName);
if (FileExtension.ToLower() == ".jpg" || FileExtension.ToLower() == ".jpeg" || FileExtension.ToLower() == ".png" || FileExtension.ToLower() == ".gif")
{
string FileName = ImageFileUploader.FileName;
//Saving the file
ImageFileUploader.SaveAs(Server.MapPath("~/Images/" + FileName));
}
}
else
{
lblMsg.Text = "Please select file to upload";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}
Problem:
After running code when file is uploaded for first time it goes in else part of code, but the same file when uploaded again it work properly and file is saved at specified location. This is happening every time of execution. I am not getting what is going wrong.
Please any one can guide me on this?
change your form tag to this if you are mot using like this:
<form action="" method="post" enctype="multipart/form-data" id="form">
// your code
</form>
Everyone thank you for your support. Finally I got the solution and end up by adding this.Page.Form.Enctype = "multipart/form-data" under Page_Load Event.
protected void Page_Load(object sender, EventArgs e)
{
this.Page.Form.Enctype = "multipart/form-data";
}

on using ajax, asp.net button control click event not working

I am using Ajax with asp.net C#. What I am trying to do is, on click of a link, a div should appear. A div contains file upload controls and a button named 'Upload Files'. When upload files button is clicked, it is checking if any of the file upload controls has files. If yes, it uploads files to some directory and updates a label to show how many files are uploaded 0 or more. Here is the screenshot to explain:
Here's the code snippet, I am using Ajax with asp.net C#
<div class="form-group row">
<asp:UpdatePanel runat="server" id="UpdatePanel1" updatemode="Conditional">
<ContentTemplate>
<div class="col-xs-5">
<% if (Session["MemberID"]!= null)
{%>
<asp:LinkButton ID="insertMore" runat="server" OnClick="insertMoreclicked">(Insert More Attachments)</asp:LinkButton>
<%} %>
</div><br />
<div id="moreUploadsDiv" runat="server" visible="false">
<br />
<asp:FileUpload ID="moreUpload1" runat="server" />
<asp:FileUpload ID="moreUpload2" runat="server" />
<asp:FileUpload ID="moreUpload3" runat="server" />
<asp:FileUpload ID="moreUpload4" runat="server" />
<asp:Button ID="uploadMoreFilesBtn" runat="server" Text="Upload" OnClick ="uploadMoreClicked" CausesValidation="false" />
<br />
<asp:Label ID="uploadInfoLbl" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
Here's the code behind file event for button:
protected void uploadMoreClicked(object sender, EventArgs e)
{
int countFiles = 0;
if (moreUpload1.HasFile)
{
moreUpload1.PostedFile.SaveAs(Server.MapPath("/Upload/") + moreUpload1.FileName);
string fn2 = moreUpload1.FileName;
bool status2 = blReg.insertFiles(fn2, FileID);
countFiles++;
}
if (moreUpload2.HasFile)
{
moreUpload2.PostedFile.SaveAs(Server.MapPath("/Upload/") + moreUpload2.FileName);
string fn2 = moreUpload2.FileName;
bool status2 = blReg.insertFiles(fn2, FileID);
countFiles++;
}
if (moreUpload3.HasFile)
{
moreUpload3.PostedFile.SaveAs(Server.MapPath("/Upload/") + moreUpload3.FileName);
string fn2 = moreUpload3.FileName;
bool status2 = blReg.insertFiles(fn2, FileID);
countFiles++;
}
if (moreUpload4.HasFile)
{
moreUpload4.PostedFile.SaveAs(Server.MapPath("/Upload/") + moreUpload4.FileName);
string fn2 = moreUpload4.FileName;
bool status2 = blReg.insertFiles(fn2, FileID);
countFiles++;
}
uploadInfoLbl.Text = countFiles + " file(s) uploaded<br/>";
}
But button click event doesn't work. Please suggest me what i am doing wrong. Thanks in Advance!

ASP.NET C# Update Panel, File Upload Control and maintaining and saving information on postback

I am designing a web page in asp.net C# named "myprofile". The structure is as follows from top to bottom: file upload control(for logo), drop down (for hotel type), a rich text box (for contact information - extra: bold, italics, hyperlink etc features), drop down (for location).
My problem is maintaining the values of file upload control and rich text box on postback. Also I am unable to insert the values in database as nothing is happening. I tried many things. Finally, I set my design as follows:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<fieldset style="width:30%">
<legend>Update Panel-1</legend>
<br />(Type of Hotel)<br /><br />
<asp:DropDownList ID="DropDownTypeOfHotel" runat="server" CssClass="cssdropdown"></asp:DropDownList>
<br />(Contact Information Here)<br /><br />
<asp:TextBox ID="RichTextBoxContactInfo" runat="server"></asp:TextBox>
<br />(Location)<br /><br />
<asp:DropDownList ID="DropDownListLocation" runat="server" CssClass="cssdropdown"></asp:DropDownList>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<fieldset style="width:30%">
<legend>Update Panel-2</legend>
<asp:Label ID="Label1" runat="server" Text="" ForeColor="Red"></asp:Label>
<br /><br />
<asp:Button ID="btnUpdate2" runat="server" Text="Update Both Panels" OnClick="btnUpdate2_Click" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
My code for the same lies here:-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadHotelType();
}
Page.Form.Attributes.Add("enctype", "multipart/form-data");
}
protected void btnUpdate2_Click(object sender, EventArgs e)
{
if (DropDownTypeOfHotel.SelectedIndex > 0)
{
if (DropDownListLocation.SelectedIndex > 0)
{
if (!string.IsNullOrEmpty(RichTextBoxContactInfo.Text))
{
Label1.Text = "Cool!";
insert();
}
else
{
Label1.Text = "Kindly add contact info!";
}
}
else
{
Label1.Text = "Kindly select location!";
}
}
else
{
Label1.Text = "Kindly select type of hotel!";
}
}
public void loadHotelType()
{
DropDownTypeOfHotel.Items.Insert(0, "--Select Type of Hotel/Supplier--");
DropDownTypeOfHotel.Items.Insert(1, "2 star");
DropDownTypeOfHotel.Items.Insert(2, "3 star");
DropDownTypeOfHotel.Items.Insert(3, "5 star");
DropDownListLocation.Items.Insert(0, "--Select Location of Hotel/Supplier--");
DropDownListLocation.Items.Insert(1, "Canada");
DropDownListLocation.Items.Insert(2, "USA");
DropDownListLocation.Items.Insert(3, "LA");
}
public void insert()
{
int img_logo = 0;
static byte[] btlogo_img;
if (FileUpload1.PostedFile.ContentLength != 0)
{
btlogo_img = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile up1 = FileUpload1.PostedFile;
up1.InputStream.Read(btlogo_img, 0, (int)FileUpload1.PostedFile.ContentLength);
img_logo = 1;
}
if (img_logo == 1)
{
con1.Close();
con1.Open();
SqlCommand cmd = new SqlCommand("insert into file values('" + FileUpload1.PostedFile.FileName + "','" + btlogo_img + "')", con1);
cmd.ExecuteNonQuery();
con1.Close();
}
else
{
Label1.Text = "Kindly select logo!";
}
}
Kindly suggest me with the same.
The easiest solution I found was to keep the controls, that loses value on postback, outside update panel and keep all other controls inside update panel.
It really worked for me!

Problem with recaptchacontrol inside updatepanel

I have a recaptchavalidator, which is inside an updatepanel:
<asp:updatepanel runat=server id=updatepanel1>
<cc1:recaptchacontrol runat=server publickey=.. privatekey=.. id=recaptchavalidator1/>
<asp:button runat=server id=button1/>
</updatepanel>
I am sure that some of you can guess what happens. For those of you who haven't experienced this before, the recaptchacontrol disappears! I have tried redirecting to the same page if the recaptchacontrol returns a false validation, but this has resulted in complex codebehind, and loss of veiwstate.
Is there a simple solution to this? I have looked over some articles on the web, but they seem to be complex and not well structured. I need to change the content of the updatepanel, so keep this in mind.
Thank you for your help.
I got this to work nicely with just one updatepanel.
<recaptcha:RecaptchaControl Theme="white" ID="recaptcha" runat="server" PrivateKey="your_pub_key "
PublicKey="your_pub_key" />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label Visible="false" ID="RecaptchaResult" runat="server" />
<asp:Button ID="RecaptchaButton" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</ContentTemplate>
</asp:UpdatePanel>
The key is to have your updatepanel set to conditional around your post button, so that you manually call the update to reload the recaptcha control from the server side.
Then, you call .update() on your panel after you've asked for the reload();
protected void btnSubmit_Click(object sender, EventArgs e)
{
recaptcha.Validate();
if (recaptcha.IsValid)
{
RecaptchaResult.Text = "Success";
RecaptchaResult.Text = "You got it!";
RecaptchaResult.ForeColor = System.Drawing.Color.Green;
RecaptchaResult.Visible = true;
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "recaptcha", "recaptcha.reload();", true);
UpdatePanel1.Update();
}
else
{
RecaptchaResult.Text = this.recaptcha.ErrorMessage;
RecaptchaResult.ForeColor = System.Drawing.Color.Red;
RecaptchaResult.Visible = true;
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "recaptcha", "recaptcha.reload();", true);
UpdatePanel1.Update();
}
}
Here is the answer that I have tried and is working:
ASP.Net, disappearing Recaptcha, UpdatePanels and Partial PostBacks: Fixed once and for all
Basically it involves creating a hidden div and using jquery to re-render the html. Also the blog post gives a nice little breakdown of the typical solutions (e.g., using RegisterClientScriptBlock with a simple reload) and why they fail.
<div runat="server" id="pbTarget" visible="false"></div>
<recaptcha:RecaptchaControl ID="recaptcha" runat="server" Theme="clean" />
code behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
recaptcha.Validate();
if (!Page.IsValid || !recaptcha.IsValid)
{
pbTarget.Visible = true;
ScriptManager.RegisterClientScriptBlock(
recaptcha,
recaptcha.GetType(),
"recaptcha",
"Recaptcha._init_options(RecaptchaOptions);"
+ "if ( RecaptchaOptions && \"custom\" == RecaptchaOptions.theme )"
+ "{"
+ " if ( RecaptchaOptions.custom_theme_widget )"
+ " {"
+ " Recaptcha.widget = Recaptcha.$(RecaptchaOptions.custom_theme_widget);"
+ " Recaptcha.challenge_callback();"
+ " }"
+ "} else {"
+ " if ( Recaptcha.widget == null || !document.getElementById(\"recaptcha_widget_div\") )"
+ " {"
+ " jQuery(\"#" + pbTarget.ClientID + "\").html('<div id=\"recaptcha_widget_div\" style=\"display:none\"></div>');"
+ " Recaptcha.widget = Recaptcha.$(\"recaptcha_widget_div\");"
+ " }"
+ " Recaptcha.reload();"
+ " Recaptcha.challenge_callback();"
+ "}",
true
);
return;
}
else
{
//normal page processing here...
Try this.
<asp:UpdatePanel ID="ContactUpdatePanel" runat="server">
<ContentTemplate>
<p>
<label>Name:</label>
<asp:TextBox ID="txtName" runat="server"
CssClass="textbox">
</asp:TextBox>
</p>
<p>
<label>Address</label>
<asp:TextBox ID="txtAddress" runat="server"
CssClass="textbox"
Height="50px"
TextMode="MultiLine">
</asp:TextBox>
</p>
<p>
<recaptcha:RecaptchaControl ID="recaptcha" runat="server"
PublicKey="public key"
PrivateKey="private key"
Theme="white" />
</p>
<p>
<asp:UpdatePanel ID="UpdatePanel2" runat="server"
ChildrenAsTriggers="false"
UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="ErrorLabel" runat="server"
EnableViewState="false"
ForeColor="Red" />
</ContentTemplate>
</asp:UpdatePanel>
<p>
</p>
<p>
<asp:Button ID="SubmitButton" runat="server"
onclick="SubmitButton_Click" Text="Submit" />
</p>
</ContentTemplate>
</asp:UpdatePanel>
Code-behind
protected void SubmitButton_Click(object sender, EventArgs e)
{
try
{
this.recaptcha.Validate();
if (recaptcha.IsValid)
{
//valid form. post it
}
else
{
ErrorLabel.Text = "Invalid Captcha. Please re-enter the words.";
ScriptManager.RegisterClientScriptBlock(
this.Page,
this.Page.GetType(),
"mykey",
"Recaptcha.reload();",
true);
UpdatePanel2.Update();
}
}
catch (Exception exception)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}
}

Categories