File is getting saved when uploaded 2nd time - c#

<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";
}

Related

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!

File uploading in update panel still refreshing

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

Retrieve Selected Checkbox Value From Previous Page

I have an asp.net webform website which stores data in a session and on the 3rd page displays the entries entered on pg1 & pg2.
On the first page the first checkboxes is pre-selected by default but if the user selects/unselects a checkbox, when the user is on the second page, there is a back button but when it's clicked I don't know how to re-show the checkboxes selected/unselected as only the default one is checked.
I'm new to using ASP and session storing so I may be doing something completely wrong. How can I resolve my situation?
My code is:
HTML
<div class="form-group">
<div class="col-xs-offset-0 col-sm-offset-4 col-sm-3">All services</div>
<div class="col-sm-1">
<asp:CheckBox ID="Step02AllServices" runat="server" Checked="True" />
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-0 col-sm-offset-4 col-sm-3">Site content uploading only</div>
<div class="col-sm-1">
<asp:CheckBox ID="Step02ContentUploading" runat="server" />
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-0 col-sm-offset-4 col-sm-3">Site content & layout checking</div>
<div class="col-sm-1">
<asp:CheckBox ID="Step02ContentLayoutChecking" runat="server" Enabled="False" />
</div>
</div>
Code Behind
protected void Step02SubmitButton_Click(object sender, EventArgs e)
{
Session["Step02AllServices"] = Step02AllServices.Checked;
Session["Step02ContentUploading"] = Step02ContentUploading.Checked;
Session["Step02ContentLayoutChecking"] = Step02ContentLayoutChecking.Checked;
Response.Redirect("/Quotation/pg3.aspx");
}
I know that is needs to be in my Page_Load just not sure how to do it.
The below is what I have for radio buttons and test fields on another page
if (txtData2.Text == string.Empty && Session["pg2"] != null)
{
txtData2.Text = Session["pg2"].ToString();
if (Session["pg2Yes"].ToString() == "Yes")
{
pg2Yes.Checked = Session["pg2Yes"].Equals("Yes");
}
if (Session["pg2No"].ToString() == "No")
{
pg2No.Checked = Session["pg2No"].Equals("No");
}
}
Let's assume that you are on page 3 and you clicked the back button which redirects you to page 2.
On load of page 2, you need to check whether it's a new load (not postback) and if it contains the values on session. If both are true, you need to get the value from session and make the checkbox selected.
So, write the following code in Page2Load
//if you are loading the new page
if (!Page.IsPostBack)
{
if(Session["Step02AllServices"] != null)
{
Step02AllServices.Checked = (bool) Session["Step02AllServices"];
//similarly assign other checkbox values as they are in session already
}
else
{
//do normal assignment
}
}
check the below simple implementation and enhance it according to your requirement and can be done using single page
aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="div1" runat="server">
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CheckBox ID="CheckBox2" runat="server" /><asp:Button ID="Button1" runat="server" Text="Next" OnClick="Button1_Click" />
</div>
<div id="div2" runat="server" visible="false">
<asp:Button ID="Button2" runat="server" Text="Back" OnClick="Button2_Click"/>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button3" runat="server" Text="Next" OnClick="Button3_Click"/>
</div>
<div id="div3" runat="server" visible="false">
<asp:Button ID="Button4" runat="server" Text="Back" OnClick="Button4_Click"/>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label4" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
cs code:
using System;
namespace WebApplication1
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
div1.Visible = false;
div2.Visible = true;
div3.Visible = false;
}
protected void Button2_Click(object sender, EventArgs e)
{
div1.Visible = true;
div2.Visible = false;
div3.Visible = false;
}
protected void Button3_Click(object sender, EventArgs e)
{
div1.Visible = false;
div2.Visible = false;
div3.Visible = true;
Label1.Text = CheckBox1.Checked.ToString();
Label2.Text = CheckBox2.Checked.ToString();
Label3.Text = TextBox1.Text;
Label4.Text = TextBox2.Text;
}
protected void Button4_Click(object sender, EventArgs e)
{
div1.Visible = false;
div2.Visible = true;
div3.Visible = false;
}
}
}

Error Object reference not set when using UpdatePanel

I had this error " Object reference not set .... " , I had checked my
code and I got that the error in UpdatePanel , when i removed it the
code worked well but I must use it to prevent all page reload .
<div>
<fieldset style="width: 498px; text-align: right; padding: 5px; direction: rtl;">
<legend>what do y think ? </legend>
<div class="add-post">
<textarea class="textarea" cols="3" rows="3" runat="server" id="txpost"></textarea>
<asp:RequiredFieldValidator ID="RVAddPost" runat="server" ForeColor="Red" ErrorMessage="*"
ControlToValidate="txpost" ValidationGroup="AddUserPost">*</asp:RequiredFieldValidator>
</div>
<asp:UpdatePanel ID="UPAddUserPost" runat="server">
<ContentTemplate>
<div class="add-post-control">
<div class="post">
<asp:Button Text="Submit" runat="server" ID="btAddPost" OnClick="btAddPost_Click" ValidationGroup="AddUserPost" />
</div>
<div class="fileUpload btn btn-primary">
<div class="fileUpload btn btn-primary">
<span>
<img src="res/images/img.png" width="38" height="27" /></span>
<input type="file" runat="server" class="upload" id="FUFile" />
</div>
</div>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btAddPost" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</fieldset>
<script type="text/javascript">
$('.textarea').focus(function () {
$(this).animate({
height: "80px"
}, 500);
$('.add-post-control').fadeIn(200);
});
</script>
</div>
Method:
protected void btAddPost_Click(object sender, EventArgs e)
{
AddpostfromFront();
}
private void AddpostfromFront()
{
if (FUFile.PostedFile.ContentLength != 0)
{
string tempVar = "~/res/Posts/" + FUFile.Value.ToString();
FUFile.PostedFile.SaveAs(Server.MapPath(tempVar));
ftier.Addpostfromfront(LoggedUserID, "4", txpost.Value, tempVar, DateTime.Now, DateTime.Now, false, false);
}
}
I think what you need to do instead of check the length of the file is to use a method that is built into PostedFile to check if there is a file to begin with.
if you look on the Microsoft page for PostedFile your code would look more like this
Private void AddpostfromFront() //I don't like your naming on this, should be AddPostFromFront
{
if (FUFile.HasFile)
{
string tempVar = "~/res/Posts/" + FUFile.Value.ToString();
FUFile.SaveAs(tempVar);
}
}
to use these methods you may have to use the ASP control instead of the HTML tag, <asp:FileUpload></asp:FileUpload> you will have to adjust the attributes to fit your situation and naming scheme. This would replace your HTML tag <input type="file" runat="server" class="upload" id="FUFile" />
I think that you are meshing two processes into one and getting confused as to what your code should be doing.
no clue what ftier is and why it has the same method name with the same bad naming scheme, or what it is doing with that information.
you should do this in 3 steps
upload the file
save the file
if you need to display the file then do so with the file that is saved, not the file that is being uploaded.

Updating the master page when the control is within an update panel on the content page

I have an application which has a control within a update panel but needs to update a part of the master page aswel - i m not sure if this can be done?
The
<asp:ScriptManager ID="ScriptManager" runat="server" />
is within the master page
and the part of the master page i want to update is the following:
<div id="divPanelMyCover" class="divPanelMyCover" runat="server">
<div class="sectionYourProtection">
<div class="sectionPadding">
<h4>Title</h4>
</div>
<div class="innerPanelMyCover">
<br/>
<ul class="bulletList" type="square">
<li><span class="spBold">Monthly Payment: </span><asp:Label ID="lblMonthlyPayment" runat="server" Text=""></asp:Label </div>
</div>
</div>
code behind:
lblMonthlyPayment.Text = Convert.ToString(application.Premium);
The lblMonthlyPayment needs to change depending on what the user selects on a content page but as the control is within an update panel it is not working.
Content page:
<asp:UpdatePanel ID="upUpSell" runat="server">
<ContentTemplate>
<div id ="divSlider" runat="server" visible="false">
<br />
<h3>If you want, you can change the amount ... </h3>
<hr />
<div class="sliderContainer">
<telerik:RadSlider id ="rdSlider" AutoPostBack="true" runat="server" Orientation="Horizontal" Width="450"
Height="70" MinimumValue="0" MaximumValue="50" LargeChange="10" TrackPosition="BottomRight"
ItemType="Tick" IsSelectionRangeEnabled="false" SelectionStart="10" SelectionEnd="30" Skin="Default" DragText="Select Premium" >
</telerik:RadSlider>
</div>
<asp:Label ID="lblValue" runat="server" Text="" Visible="false"></asp:Label>
</div>
c#
protected void Page_Load(object sender, EventArgs e)
{
//if (!Page.IsPostBack)
//Pre-populate the screen with data from ApplicationBO
ApplicationBO application = (ApplicationBO)Session["Application"];
if (!Page.IsPostBack)
{
if (Session["Application"] == null)
application = new ApplicationBO();
else
application = (ApplicationBO)Session["Application"];
lblclientName.Text = application.FirstName;
rdSlider.Value = Convert.ToDecimal(application.Premium);
lblMonthlyPayment.Text = Convert.ToString(application.Premium);
}
divSlider.Visible = true;
string upsellValue = Convert.ToString(application.Premium);
if (divSlider.Visible == true)
{
upsellValue = Convert.ToString(rdSlider.Value);
// Save the current page information
application.Premium = Convert.ToDecimal(upsellValue);
}
Thanks in advance...
Wrap the label with an UpdatePanel with UpdateMode="Always"

Categories