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!
Related
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;*/
}
}
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!
in my HTML, I have a fileUpload button where you can choose a file to upload a file and then once you click pbcUploadBtn, it goes through validation in Validation.CheckWellFormed(...). The validation method returns an empty string if the file is fine or a string with the first error in the file otherwise. How can I have this display on my page using jQuery or js, etc.?
<div class="upload">
<asp:FileUpload ID="fileUpload" class="btn" runat="server" />
<asp:Button ID="pbcUploadBtn" class="btn btn-primary" runat="server" Text="Upload" onclick="uploadBtnClick" />
</div>
protected void uploadBtnClick(object sender, EventArgs e)
{
if (this.fileUpload.HasFile)
{
// file gets uploaded to szSaveToPath
Validation.CheckWellFormed(szSaveToPath);
//do things
}
}
You don't need to use js in this case.
You can add a label and change it's text property:
<div class="upload">
<asp:FileUpload ID="fileUpload" class="btn" runat="server" />
<asp:Button ID="pbcUploadBtn" class="btn btn-primary" runat="server" Text="Upload" onclick="uploadBtnClick" />
<asp:Label runat="server" ID="lblStatus"></asp:Label>
protected void uploadBtnClick(object sender, EventArgs e)
{
if (this.fileUpload.HasFile)
{
// file gets uploaded to szSaveToPath
lblStatus.Text = Validation.CheckWellFormed(szSaveToPath);
//do things
}
}
Scenario: I have a modal-style div that will be shown when the user clicks a button. At the time the div is shown, I need to get some data from the back-end to fill in some fields. Additionally, I'd like to use the jQuery method I use for all my modal windows (fades in the modal div, displays a background div as well as enabling the use of ESC key or "click offs" to close the modal).
It looks something like this:
<asp:ScriptManager ID="sc" runat="server" />
<asp:UpdatePanel ID="updForm" runat="server">
<ContentTemplate>
<h4>Testing jQuery calls combined with code behind actions</h4>
<div class="pad-content">
<asp:LinkButton ID="lnkShowIt" runat="server" OnClick="lnkShowIt_Click" Text="Load Form" OnClientClick="showForm()" />
<asp:Panel ID="pnlPopup" ClientIDMode="Static" runat="server" CssClass="box-modal" style="width:500px;display:none;z-index:1001">
<div class="header">Edit Estimate X</div>
<div class="content">
<div class="window">
<h5>Test Form</h5>
<asp:TextBox ID="tbxTime" runat="server" />
<br />
<asp:TextBox ID="tbxText" runat="server" Width="150px" />
<br />
<asp:LinkButton ID="lnkValidate" runat="server" CssClass="link-button-blue" Text="Validate" OnClick="lnkValidate_Click" />
</div>
</div>
</asp:Panel>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div id="backgroundPopup"></div>
So ... lnkShowIt calls both the jQuery (which will show pnlPopup) as well as the C# (which will populate tbxTime).
jQuery method actually just calls another method from a common js library I have that does the modal window stuff - I don't think that actual code is the problem but here is the simple function used for this page:
<script type="text/javascript" language="javascript">
function showForm() {
loadPopup('#pnlPopup');
}
</script>
Code behind methods look like this:
protected void lnkShowIt_Click(object sender, EventArgs e)
{
tbxTime.Text = System.DateTime.Now.Second.ToString();
}
protected void lnkValidate_Click(object sender, EventArgs e)
{
if (tbxTime.Text == tbxText.Text)
{
Response.Redirect("DynamicBoxesWithJQuery.aspx?mode=success");
}
else
{
tbxText.Style["border"] = "1px solid red";
}
}
I'm able to generate some level of success by doing the following but it seems like just a major hack and I have to assume there's a better approach:
protected void lnkShowIt_Click(object sender, EventArgs e)
{
tbxTime.Text = System.DateTime.Now.Second.ToString();
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenEditor", "<script type='text/javascript'>loadPopup('#pnlPopup');</script>", false);
}
protected void lnkValidate_Click(object sender, EventArgs e)
{
if (tbxTime.Text == tbxText.Text)
{
Response.Redirect("DynamicBoxesWithJQuery.aspx?mode=success");
}
else
{
tbxText.Style["border"] = "1px solid red";
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenEditor", "<script type='text/javascript'>loadPopup('#pnlPopup');</script>", false);
}
}
It seems like it should be easier than this, but the way the UpdatePanel keeps redrawing (and thus resetting the display:none on pnlPopup) is really causing me fits.
Thanks in advance
Solution I just found: putting the LinkButton in its own UpdatePanel and then the form in its own UpdatePanel and making sure the div that is the actual popup box is not in an UpdatePanel at all.
<h4>Testing jQuery calls combined with code behind actions</h4>
<div class="pad-content">
<asp:UpdatePanel ID="updLink" runat="server">
<ContentTemplate>
<asp:LinkButton ID="lnkShowIt" runat="server" OnClick="lnkShowIt_Click" Text="Load Form" OnClientClick="showForm()" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="pnlPopup" ClientIDMode="Static" runat="server" CssClass="box-modal" style="width:500px;display:none;z-index:1001">
<div class="header">Edit Estimate X</div>
<div class="content">
<asp:UpdatePanel ID="updForm" runat="server">
<ContentTemplate>
<div class="window"style="min-width:500px;">
<h5>Here is a Test Form</h5>
<label>Time:</label>
<asp:TextBox ID="tbxTime" runat="server" />
<br />
<asp:Label ID="lblText" AssociatedControlID="tbxText" runat="server" ViewStateMode="Disabled">Text:</asp:Label>
<asp:TextBox ID="tbxText" runat="server" Width="150px" />
<br />
<asp:LinkButton ID="lnkValidate" runat="server" CssClass="link-button-blue" Text="Validate" OnClick="lnkValidate_Click" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Panel>
</div>
Seems to do the trick without any Script Registers from the codebehind
Here's the markup:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="well well-large">
<form class="navbar-form pull-left">
<asp:FileUpload ID="test" runat="server" CssClass="input-small" />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" CssClass="btn" OnClick="btnUpload_Click" />
</form>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnUpload" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Panel runat="server" ID="panAlert" Visible="false">
<div class="alert alert-success" id="divAlert" runat="server">
<button id="Button1" runat="server" type="button" class="close" data-dismiss="alert">×</button>
You shouldn't see this message!
</div>
<asp:Panel runat="server" ID="panMarquee" Visible="true">
<div id="Div1" runat="server" class="progress progress-success progress-striped">
<div id="ProgressBar" runat="server" class="bar" style="width: 100%"></div>
</div>
</asp:Panel>
</asp:Panel>
When the btnUpload button is clicked, the server code is supposed to determine if the FileUpload control has a file. If it does, it will change the visibility of the Panel control to true. It works fine outside of the UpdatePanel.
Here's the server code:
protected void btnUpload_Click(object sender, EventArgs e)
{
this.SetMessage(Message.Success);
try
{
if (this.test.HasFile)
{
string filename = Path.GetFileName(GetUB04Doc.FileName);
//test.SaveAs(Server.MapPath("~/") + filename);
this.SetMessage(Message.Success);
}
}
catch (Exception ex)
{
//TODO: Do something with th exception
this.SetMessage(Message.Fail);
}
finally
{
//this.GetUB04Doc.Dispose();
}
}
private enum Message { Success, Fail }
private void SetMessage(Message msg)
{
if (msg == Message.Success)
{
this.divAlert.InnerText = "Well done! The document appears to have uploaded successfully. Please wait...";
this.divAlert.Attributes.Add("class", "alert alert-success");
}
else
{
this.divAlert.InnerText = "Oh snap! Something broke. Please contact IT right away.";
this.divAlert.Attributes.Add("class", "alert alert-error");
}
this.panAlert.Visible = true;
}
I tried putting the Panel in the ContentTemplate section as well, but the results were the same.
Any ideas on what I'm doing wrong here?
You should surround the area which you are modifying from an async postback in another UpdatePanel with UpdateMode is set to Conditional. Then update the other manually from codebehind:
<asp:UpdatePanel ID="panAlertUpdatePanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:Panel runat="server" ID="panAlert" Visible="false">
<!-- ....
codebehind:
// ...
this.panAlert.Visible = true;
panAlertUpdatePanel.Update()
Side-note: As #Belogix has already commented, you should use an AsyncFileUpload control in an UpdatePanel since a regular FileUpload control it's not supported with an asynchronous postback.
MSDN:
Controls that Are Not Compatible with UpdatePanel Controls:
...
FileUpload and HtmlInputFile controls when they are used to upload files as part of an asynchronous postback.
...
To use a FileUpload or HtmlInputFile control inside an UpdatePanel
control, set the postback control that submits the file to be a
PostBackTrigger control for the panel. The FileUpload and
HtmlInputFile control can be used only in postback scenarios.
you need to put PostBackTrigger instead of AsyncPostBackTrigger like this. <asp:PostBackTrigger ControlID="btnUpload" />