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

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!

Related

ASP.NET C# FileUpload inside UpdatePanel with Postback

currently i'm trying to upload an image via a FileUpload and store it in a database. My problem is that when i click the upload-button, i always get a System.NullReferenceException when trying to upload.
Now i know that there are issues with asp-FileUploads inside an UpdatePanel - so i set the upload-button as an PostBackTrigger which causes a full postback - but it's still not working.
Thats what i got so far:
<asp:UpdatePanel ID="Update_woundpic" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:PostBackTrigger ControlID="woundpic_upload" />
</Triggers>
<ContentTemplate>
<div class="col-md-3">
<h3 class="label2">Upload
<small class="text-muted">maximal 5MB</small>
</h3>
<asp:FileUpload ID="uploadWoundImage" runat="server" />
<br />
<asp:LinkButton ID="woundpic_upload" runat="server" OnClick="btn_Upload_Click" CssClass="btn3d btn btn-default btn-lg"><span aria-hidden="true" class="glyphicon glyphicon-upload"></span> Hochladen</asp:LinkButton>
<asp:Label ID="lbl_success" runat="server" Text="Upload erfolgreich!" CssClass="uploadSuccess" Visible="False"></asp:Label>
<asp:Label ID="lbl_error" runat="server" Text="Upload nicht erfolgreich!" CssClass="uploadFailure" Visible="False"></asp:Label>
<br />
<br />
</div>
</ContentTemplate>
</asp:UpdatePanel>
And this is my method to upload the image / file:
protected void btn_Upload_Click(object sender, EventArgs e)
{
byte[] imgByte;
using(BinaryReader reader = new BinaryReader(uploadWoundImage.PostedFile.InputStream))
{
imgByte = reader.ReadBytes(uploadWoundImage.PostedFile.ContentLength);
}
DateTime imageUpload = DateTime.Now;
string imageFormat = uploadWoundImage.PostedFile.ContentType;
string imageName = Path.GetFileName(uploadWoundImage.PostedFile.FileName);
_db.SaveWoundImage(imgByte, imageFormat, imageName, imageUpload);
}
Now, if i click the button the line
using(BinaryReader reader = new BinaryReader(uploadWoundImage.PostedFile.InputStream))
throws the System.NullReferenceException, so i don't know why the file isn't found even with a full postback.
Thanks for any help!

ASP.NET TextBox won't add text from C#

I am trying to do a multi Client - Server application. After I did some of the basic controls and functions with Windows Forms I thought to add a WebPage to my Client side.
I created a new project and edited it and it works ok, the page is connecting to the server and it receives the messages I send from the web page.
The problem I get when I need to post messages on a textbox on the web page. I searched on some pages here, on the internet and I can't find a good solution for my problem. I alose used the Page.IsPostBack but it didn't work, then I added an UpdatePanel because the page was refreshing when I clicked the buttons but that didn't work either... Now I am out of ideas.
Can anybody suggest how should I do this ? My code behind is C# and I don't know how to parse these details to JavaScript or jQuery, so any of you have some details on how to that it will also be appreciated.
Thanks in advance.
And also I will post anything needed if there is important for this question.
EDIT (Added code):
public void btnSend_Click(object sender, EventArgs e)
{
if (tbSendMessage.Text.Length > 0)
{
string message = tbSendMessage.Text;
byte[] outStream = Encoding.ASCII.GetBytes(message + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
tbSendMessage.Text = string.Empty;
}
}
private void getMessage()
{
while (true)
{
try
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[70000];
buffSize = clientSocket.ReceiveBufferSize;
serverStream.Read(inStream, 0, buffSize);
string returndata = Encoding.ASCII.GetString(inStream);
//tbReceivedMessages.Text += returndata + "\n";
ShowMessage(returndata);
}
catch (Exception ex)
{
ShowAlert("Connection lost.\n" + ex.Message);
//ShowMessage("Conexiunea cu serverul s-a pierdut.\n" );
serverStream.Close();
return;
}
}
}
private void ShowMessage(string message)
{
sb.AppendLine(message);
tbReceivedMessages.Text += sb;
}
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %></h2>
<p>
<asp:UpdatePanel ID="UpdatePanelConnect" runat="server">
<ContentTemplate>
<asp:Label ID="lblUsername" runat="server" Text="Enter username:"></asp:Label>
<asp:TextBox ID="tbUsername" runat="server"></asp:TextBox>
<asp:Button ID="btnConnect" runat="server" OnClick="btnConnect_Click" Text="Connect" />
</ContentTemplate>
</asp:UpdatePanel>
</p>
<p> </p>
<p>
<asp:UpdatePanel ID="UpdatePanelConnected" runat="server">
<ContentTemplate>
<asp:TextBox
ID="tbReceivedMessages"
runat="server"
Height="250px"
TextMode="MultiLine"
Width="250px"
MaxLength="2000000"
ReadOnly="True"></asp:TextBox>
</p>
<p> </p>
<p>
<asp:TextBox ID="tbSendMessage" runat="server"></asp:TextBox>
<asp:Button ID="btnSend" runat="server" OnClick="btnSend_Click" Text="Send" />
</ContentTemplate>
</asp:UpdatePanel>
</p>
</asp:Content>
If you want two server controls to communicate each other via Ajax, you will need to place them in same UpdatePanel.
FYI: If you are new to ASP.Net Web Form, do not use UpdatePanel yet. Instead, make it work with regular post back.
<asp:UpdatePanel ID="UpdatePanelConnect" runat="server">
<ContentTemplate>
<asp:Label ID="lblUsername" runat="server" Text="Enter username:"></asp:Label>
<asp:TextBox ID="tbUsername" runat="server"></asp:TextBox>
<asp:Button ID="btnConnect" runat="server" OnClick="btnConnect_Click" Text="Connect" />
<asp:TextBox
ID="tbReceivedMessages"
runat="server"
Height="250px"
TextMode="MultiLine"
Width="250px"
MaxLength="2000000"
ReadOnly="True"></asp:TextBox>
</p>
<p> </p>
<p>
<asp:TextBox ID="tbSendMessage" runat="server"></asp:TextBox>
<asp:Button ID="btnSend" runat="server" OnClick="btnSend_Click" Text="Send" />
</ContentTemplate>
</asp:UpdatePanel>
public void btnSend_Click(object sender, EventArgs e)
{
if (tbSendMessage.Text.Length > 0)
{
string message = tbSendMessage.Text;
// This code won't work.
/*byte[] outStream = Encoding.ASCII.GetBytes(message + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
tbSendMessage.Text = string.Empty;*/
}
}

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

ASP AJAX TABS Sys.InvalidOperationException ERROR

Hello everyone I have a webform which uses ajax tabs inside the content teplte of the tab I put an user control here is an exapmple
<ajaxtoolkit:tabcontainer id="StyledTabContainer" runat="server" activetabindex="0"
width="600px" cssclass="MyTabStyle">
<!-- Overview Tab -->
<ajaxToolkit:TabPanel HeaderText="Overview" CssClass="none" runat="server" ID="TabPanel1" OnClientClick="PanelClickHide">
<ContentTemplate>
<div>
<h3>Overview</h3>
<p>
<over:Overview id="overview" runat="server" />
</p>
</div>
</ContentTemplate>
</ajaxToolkit:TabPanel>
<!-- Pre-test Tab -->
<ajaxToolkit:TabPanel HeaderText="Pre-test" runat="server" ID="TabPanel2" OnClientClick="PanelClickHide">
<ContentTemplate>
<h3>Pre-test</h3>
<br />
<p>
<pre:PreTest id="pretest" runat="server" />
</p>
</ContentTemplate>
</ajaxToolkit:TabPanel>
<!-- Webcast -->
<ajaxToolkit:TabPanel HeaderText="Webcast" runat="server" ID="TabPanel3" OnClientClick="PanelClick">
<ContentTemplate>
<h3>Webcast</h3>
<br />
<p id="pvisible" style="display:none">
<vid:Video id="vid1" runat="server"/>
</p>
</ContentTemplate>
</ajaxToolkit:TabPanel>
<!-- Post-test Tab -->
<ajaxToolkit:TabPanel HeaderText="Post-test" runat="server" ID="TabPanel4" OnClientClick="PanelClickHide">
<ContentTemplate>
<h3>Post-Test</h3>
<br />
<p>
<post:Post id="post" runat="server" />
</p>
</ContentTemplate>
</ajaxToolkit:TabPanel>
</ajaxtoolkit:tabcontainer>
inside the user control I have a submit button.
on a webform where ajax tabs are located i control which tab to open or close here is example
if (status.Part1StartDate != null)
{
StyledTabContainer.ActiveTabIndex = 1;
TabPanel1.Enabled = false;
TabPanel2.Enabled = true;
TabPanel3.Enabled = false;
TabPanel4.Enabled = false;
TabPanel5.Enabled = false;
TabPanel6.Enabled = false;
}
if (status.Part1Done == true)
{
StyledTabContainer.ActiveTabIndex = 2;
TabPanel1.Enabled = false;
TabPanel2.Enabled = false;
TabPanel3.Enabled = true;
TabPanel4.Enabled = false;
TabPanel5.Enabled = false;
TabPanel6.Enabled = false;
}
whenever i Click a button inside the user control which is inside the content template I get this error.
Microsoft JScript runtime error: Sys.InvalidOperationException:
Handler was not added through the Sys.UI.DomEvent.addHandler method.
Any help please.....
Thank You

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