Need some idea about upload a file using ajax - asp.net

i want to upload an image on my host in my aspx page.but can i do that with ajax?(i mean,no postback done during the upload).
i look at the gmail file uploader,the classic mode used flax(this is bad idea) but i can understand about the modern mode?!!
according to my search in Google it is impossible for security reasons may be occure
some body help me about this issue."upload a file using ajax"

you can do like this.. using ajax .....
STEP 1: first create an upload form in separate page which is like this (myIframe.html)
<form method="POST" target="_self" enctype="multipart/form-data" action="main.aspx">
<input type="file" name="fileUpload" />
<input type="submit" value="UPLOAD" />
</form>
STEP 2: In main page (main.aspx), you have to put an iframe and loaded that page in it. you can also made borders invisible so it did not look like it is an iframe.
<iframe name="iUploadFrame" src="myIframe.html" frameborder="0" onload="iUploadFrameLoad();"></iframe>
Note that this is specifying onload event handler function of javascript. that one will explain it below.
STEP 3: For testing, in main.aspx and in UpdatePanel with a button and label like this:
<asp:UpdatePanel ID="pnlMain" runat="server">
<ContentTemplate>
<asp:Label id="lblMessage" runat="server" />
<asp:Button id="btnUploadComplted" runat="server" style="visibility:hidden;" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnUploadCompleted" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Note that if you want you can hide the button using CSS style, but not setting visible=”False” attribute. This is because if you want to have the button html in the output document and would want to trigger the ajax callback via that button.
STEP 4: you can define the click event hander of the button in the codebehind like this :
protected void btnUploadCompleted_Click(object s, EventArgs e) {
lblMessage.Text = "UPLOAD PROCESS COMPLETED SUCCESSFULLY";
}
STEP :5 Now, to save file you can do write the code in the code-behind like this:
protected void Page_Load(object s, EventArgs e) {
if ((Request.Files.Count == 1)) {
// process to save file
Response.Write("SUCCESS");
Response.End();
}
}
STEP:6 Now all that we need to do is create javascript function to integrate the process into ajax implementation. The event will trigger when upload process is complete, and it will, in turn, triggers btnUploadCompleted’s click event, which is responsible for making our ajax call.
<script type="text/javascript">
function iUploadFrameLoad() {
if (window.iUploadFrame.document.body.innerHTML == "SUCCESS") {
document.forms[0].elements[btnUploadCompleted].click();
}
}
</script>
I hope it will helps you...

Related

How do I "print" an image to a ASP.NET update panel page?

I create a chart, and save it in the path server.mappath("/images/chart/chartname.png"), and if I go to the path, the image is there, and I can open it on my computer, but what I would really like to do is display the image on the page after I create it, preferably asynchronously. I've tried putting a asp:image control in the update panel and changing the url, but that doesn't work. I've tried a bunch of different ways, if someone could point me to the right direction, that would be great. I won't post any code simple because what I have so far IS working. Once I start attempting to print the image I'll post snippets if I have answers.
Edit: Here is some code
The button event that starts the whole thing:
Protected Sub btnCreate_Click(sender As Object, e As EventArgs) Handles btnCreate.Click
Dim worker As New backgroundWorker
'Check input
worker.RunWorker({})
Session("worker") = worker
Timer1.Enabled = True
End Sub
This starts the worker, which generates the chart fine, and starts the timer which is used to update the panel. Eventually in that code, this happens
Dim imgpath As String = Server.MapPath("images/chart/test.png")
chart.SaveImage(imgpath, ChartImageFormat.Png)
chartImg.ImageUrl = "~/images/chart/test.png"
Now, I know that the panel is being updated after this code is executed, because I output some messages to a multiline textbox, and they do appear. All these controls are also in the contentTemplate of the updatePanel.
Setting the ImageUrl property of an ASP.Net image control, while within and update panel, should do the trick without having to use Javascript, although that method can be very efficient. UpdatePanels tend to be "heavy", that is the ScriptManager, UpdatePanel, and ASP.Net ViewState tend to send a lot of information back and forth via their AJAX methods. You can see what I mean by using Fiddler to watch your web traffic.
That being said, I was able to achieve the desired effect in the following manner. I have two static images, Image1.jpg and Image2.jpg, but it should work with your dynamically generated image, as long as the URL is correct.
Here's the text of my ASPX page:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl="~/Image1.jpg" Width="300"></asp:Image><br />
<asp:Button runat="server" ID="btnSwitchImage" Text="Switch" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
And here is the code-behind:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e )
{
btnSwitchImage.Click += new EventHandler( btnSwitchImage_Click );
}
void btnSwitchImage_Click( object sender, EventArgs e )
{
Image1.ImageUrl = "~/Image2.jpg";
}
}
As long as the button and image controls are within the UpdatePanel's ContentTemplate everything should be relayed via AJAX. Once again, use Fiddler to confirm this.
If this example works for you but you still can't get your application working try posting some code in your question. It might help everyone analyze the problem directly.
As per my experience uploading of files does not work in asynchronous mode.You should use Jquery library to upload file asynchronously.
Check this link.
http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
I do not know ajax but you can do it with the help of javascript. Here is the code I tested on my system which works fine.
<body>
<p>
welcome to judge site</p>
<form id="form1" runat="server">
<script language="javascript" type="text/javascript">
function PrintImage()
{
printWindow = window.open ("", "mywindow","location=1,status=1,scrollbars=1,width=600,height=600");
printWindow.document.write("<div style='width:100%;'>");
printWindow.document.write("<img id='img' src='" + document.getElementById('iconId').src + "'/>");
printWindow.document.write("</div>");
printWindow.document.close();
printWindow.print();
}
</script>
<div>
<img id="iconId" alt="photo" src="iconId.png" style="width: 500px; height: 360px" /><br />
<input type="button" id="btnPrint" value="Print Image" onclick="PrintImage()" />
</div>
</form>
There are other more examples you can find on following link (Above code is also from this source but edited by me to make it work on my system)
Visit http://forums.asp.net/p/1463001/3369521.aspx

Difference between button and asp:button onclick

I am new to developing in asp.net for making web sites.
What is the difference between an asp:Button and an input button?
Code 1
aspx code
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
Codebehind
protected void Button1_Click(object sender, EventArgs e)
{
//Do somthing
}
Code 2
aspx code
<input id="Submit1" type="submit" value="submit" onclick="return Submit1_onclick()" />
<script language="javascript" type="text/javascript">
// <![CDATA[
function Submit1_onclick() {
//Do somthing
}
// ]]>
</script>
The first code it is a server side code. When you add a tag asp:button in your webform, the asp.net will render an input type="button" for you and when you click this button, it will submit a post to the same page (this is called postback) and will processing the life cycle and asp.net event associated with this button. The same is valid for every server control such as TextBoxes (render input type='text'), Panels (renders divs), Checkboxes (render input type='checkbox'), Labels (render spans) etc...
In the second code, you have the code that first one will render (an input type = 'button'), but associated with an event in the client-side javascript.
You can also associate a client-side event in a tag asp:button, take a look at the OnClientClick property.
asp:Button is an asp.net server control which fire an event on the server side.
<input id="Submit1" type="submit"
is a client side button of type submit,
but it can act as a server side button as well by adding
runat="server" and onserverclick="eventname"
The first is a server side control and the event handler is executed on the server in C#. Clicking the button will cause a postback and all information in the form will be posted to the server for processing, including a call to the click event handler.
The second is fully client side and the event handler is executed in the browser in JavaScript.
to my understanding you have to keep in mind that there is a cliend side code that will execute, for example javascript in your browser, and asp/c# code that will execute on the server.
So having this control:
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
Button1_Click will execute on the server, in microsoft world it is IIS, on the other hand
you have just a pure html control, where you hook up a javascript function for the click event
<input id="Submit1" type="submit" value="submit" onclick="return Submit1_onclick()" />
So the server side has nothing to do with this part, this code will execute on your machine, in your browser.
A mí me funcionó así:
1.- En el botón:
<input type="submit" id="btnAccept" value="Log In" runat="server" onserverclick="btnAccept_Click">
2.- En el codebehind:
Protected Sub btnAccept_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

Load specific part in webpage?

See below image first.
we have one sidebar navigation(ajax accordion control asp.net)
now when ever user click on link inside side bar related page(content) should display in Content goes here region.
As per given instruction entire page should not be refreshed or in other word in Back Button should not work(In Internet Explorer).
what should be the way to achieve this functionality?
what should be the best suggestion for that?
EDIT: navigation tree is inside MasterPage and Content goes region is in side content page of master page
please suggest me.....
thank you so much....
The Easiest way is to Wrap your side navigation & the Content placeholder in an UpdatePanel. Set the TreeView in the side bar as the UpdateTrigger for the update Panel. But, this approach is a little inefficient.
A slightly better way is ti just wrap the Content Placeholder in an Update Panel, along with a HiddenField in it. Upon a selection in the sidebar, update the HiddenField Value with JavaScript and then refresh the update Panel.
According to:
As per given instruction entire page should not be refreshed or in other word in Back Button should not work(In Internet Explorer).
And
sidebar tree view is in master page and Content goes here region is content page
If my understanding is correct, I think you do not need to place your TreeView control in your master page because you only want one page loading dynamically the content based on the selection of your tree view. So...Why is this important? Well if you place your tree view in your page you can use an UpdatePanel to avoid full posts.
Output of the following code
The following code covers the next points:
A TreeView control is embedded in a UserControl and placed in an ASPX page (left side)
The menu contorl exposes an event that is raised whenever the selected node changes, this event is handled in the ASPX page to dynamically load user controls depending on the user selection on the right side of the page, only one content is loaded at a time.
The controls are embedded in an UpdatePanel therefore you won't change your page and your back button in your browser won't be affected
Note: the user controls keep their state across post backs
(I'm not sure if this is the best way to do it, perhaps you could try to find a solution using only ajax, and avoid the use of the evil updata panels, but certainly this is a way to do it)
I'll try to simplify the code to reduce the size of the post, I will just post the code of one user control, the other one is exactly the same I just changed its title to difference them on the page
ASCX Menu
<asp:TreeView ID="TreeView1" runat="server" onselectednodechanged="Unnamed2_SelectedNodeChanged">
<Nodes>
<asp:TreeNode Text="link1" />
<asp:TreeNode Text="link2" />
</Nodes>
<SelectedNodeStyle Font-Bold="True" Font-Italic="True" />
</asp:TreeView>
ASCX Menu code behind
public event Action<string> MenuChanged = delegate { };
protected void Unnamed2_SelectedNodeChanged(object sender, EventArgs e)
{
this.MenuChanged(this.TreeView1.SelectedNode.Text);
}
ASPX
<asp:ScriptManager runat="server" ID="sm" />
<asp:UpdatePanel runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:HiddenField runat="server" ID="currentControl" />
<table border="0" cellpadding="0" cellspacing="0" width="90%" align="center">
<tr>
<td style="width:50%; background-color: Silver">
<menu:TreeViewMenu runat="server" ID="myTreeViewMenu" OnMenuChanged="myTreeViewMenu_MenuChanged" />
</td>
<td style="width:50%; background-color: Aqua">
<p>Result:</p>
<asp:Panel runat="server" ID="myPanel">
</asp:Panel>
<asp:Label ID="lblMessage" runat="server" />
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
ASPX code behind
protected void Page_Init(object sender, EventArgs e)
{
if (this.IsPostBack)
{
var cc = this.Request.Form["currentControl"];
if (!string.IsNullOrWhiteSpace(cc))
{
var uc = this.LoadControl(this.Server.HtmlDecode(cc));
this.myPanel.Controls.Add(uc);
}
}
}
protected void myTreeViewMenu_MenuChanged(string e)
{
this.myPanel.Controls.Clear();
switch (e)
{
case "link1":
var cc1 = "~/Content1.ascx";
this.currentControl.Value = this.Server.HtmlEncode(cc1);
var uc1 = this.LoadControl(cc1);
this.myPanel.Controls.Add(uc1);
this.lblMessage.Text = "Updated from: link1";
break;
case "link2":
var cc2 = "~/Content2.ascx";
this.currentControl.Value = this.Server.HtmlEncode(cc2);
var uc2 = this.LoadControl(cc2);
this.myPanel.Controls.Add(uc2);
this.lblMessage.Text = "Updated from: link2";
break;
default:
this.lblMessage.Text = "Updated from default: " + e;
break;
}
}
ASCX
<h1>Content 1</h1>
<asp:TextBox runat="server" ID="txt" />
<asp:Button Text="Process data..." runat="server" OnClick="button_Click" />
<asp:Button Text="Just post" runat="server" />
<asp:Label ID="lblMessage" runat="server" />
ASCX Code Behind
protected void button_Click(object sender, EventArgs e)
{
this.lblMessage.Text = this.txt.Text;
}
You can simply copy-paste this code to test it yourself, this should work
Jupaol's answer works fine but 1 thing need to mention, I came across the problem after implemented Jupaol's idea, the first time I called the user control immediately after I click menu, the button with in the ascx works fine, but if I switch to 2nd one, first click of the button on the 2nd control will not fire on first click, this is because we do not have a "static" ID of the control. It took me almost 3 days to finally figure out why this is happening. so here's part of my code to make. I'm leaving this message in hope that anyone who read this afterwards will make the use of it.
if (!string.IsNullOrEmpty(controlPath))
{
PlaceHolder1.Controls.Clear();
UserControl uc = (UserControl)LoadControl(controlPath);
/**note below LastLoadedControl is anything that could
* be unique to the called control so every time when call back
* it will not confuse the back end so the first fire of eg. a button
* on that loaded control will work
*/
uc.ID = LastLoadedControl;
PlaceHolder1.Controls.Add(uc);
}
I'll also need to thank Jupaol's great contribution so that I can get my site running.

UpdateProgress won't show when causing an UpdatePanel to refresh with javascript

I have an UpdatePanel and inside the update panel I have a button. The updatepanel also has an updateprogress control tied to it in order to display a loading graphic when the updatepanel does a postback.
If I click the button in the update panel then the progress loader shows up just fine. However, if I select the button with jQuery and do .click() the loader doesn't show up. The panel does post back and load content correctly but the progress loader doesn't trigger.
Any ideas why this would be?
I just have tried your scenario. It works fine here.
Here is the html
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:UpdateProgress runat="server" ID="UpdateProgress1">
<ProgressTemplate>
<img src="Images/ajax-loader.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<input id="btnTest" title="JQuery Click" onclick="ClickButton1()" type="button" value="JQuery Click" />
<script type="text/javascript">
function ClickButton1() {
// alert('#<%=Button1.ClientID %>');
$('#<%=Button1.ClientID %>').click();
}
</script>
Here is the back end code to show loading image for 5 seconds
protected void Button1_Click(object sender, EventArgs e)
{
Thread.Sleep(5000);
}
I never did find the answer to this question but it doesn't matter. I learned that update panels only make one request at a time for a reason. The page life-cycle and viewstate cannot be broken, therefore asynchronous requests can only be made one at a time.
MVC for the win.

FileUpload in FormView inside an UpdatePanel

The Scenario:
I have an ASP.Net webpage which I intend to use for letting the user(not the real users, but content manager basically) insert and edit the records in a table using a FormView. This FormView is inside an UpdatePanel, as I'm also using cascading dropdownlists to let the user select some values.
Now, this FormView also contains 4 FileUpload controls, and as you might know that these fileupload controls require a full postback since most browsers do not let Javascript access the disk. So, this problem would have been solved by doing something like:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="InsertButton" />
<asp:PostBackTrigger ControlID="UpdateButton" />
</Triggers>
<ContentTemplate>....</ContentTemplate>
</asp:UpdatePanel>
Edit: Forgot to add that the fileuploading takes place in the OnUpdating and OnInserting events of the SqlDataSource.
The Problem:
Since the InsertButton and the UpdateButton reside inside the Formview, I cannot directly access their ID's through markup. And MSDN says that:
Programmatically adding
PostBackTrigger controls is not
supported.
Please suggest some solution to make this work. Any insight on the matter is highly appreciated. Thanks.
P.S.- A workable solution for me was to set the UpdatePanel's PostBackTrigger as the whole FormView itself:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="FormView1" />
</Triggers>
<ContentTemplate>....</ContentTemplate>
</asp:UpdatePanel>
But now due to a bit of change in requirements, this solution(if you call it a solution) is not acceptable.
Have you given a though about using Iframe for doing the postback ? something like:
<iframe name="uploader" id=uploader
src="uploaderSender.aspx?AllowedExtension=<%= AllowedExtension %>&StoringPath=<%= StoringPath %>&StoringFileName=<%= StoringFileName %>&OldFileName=<%= OldFileName %>&MaximumSize=<%= MaximumSize %>"
width="450" height="50" frameborder=0 scrolling=no >
</iframe>
with uploaderSender.aspx like :
<form action="UploaderReceiver.aspx" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" onchange="document.getElementById('IsFileUploading').style.visibility = 'visible'; document.forms[0].submit()"/>
<span id="IsFileUploading" style="visibility: hidden">
<asp:Image ID="Image1" runat="server" ImageUrl="~/immagini/Ajax-loader.gif" />
</span>
</form>
and UploaderReceiver.aspx like :
protected void Page_Load(object sender, EventArgs e)
{
//if there is one file to process
if (Request.Files.Count > 0)
//create the folder if it does'nt exists and returns the local path to get it
string StoringPathToBeSaved = StoringPath.GetFolderPath();
// append the name of the file to upload to the path.
StoringPathToBeSaved = StoringPathToBeSaved + StoringFileName + Extension;
Request.Files[0].SaveAs(StoringPathToBeSaved);
}
this is just bits of code just for you to figure out if you would be interested in this way of dealing with the upload, I can give you more if you want after.
see you, and good luck with your code,
Yay!! Finally got it to work!
Here's How:
Well contrary to what MSDN says, we can in fact add PostBack Triggers Programmatically. Not necessarily to the UpdatePanel, but to the ScriptManager.
After hours of playing around, here's what worked:
We are not able to access controls inside a FormView, untill the template has been rendered, so we can only add postback triggers after the formview's OnDataBound Event.
protected void FormView1_DataBound(object sender, EventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.Edit)
{
LinkButton lb = (LinkButton)FormView1.FindControl("UpdateButton");
ScriptManager.GetCurrent(Page).RegisterPostBackControl(lb);
}
//Similarily you can put register the Insert LinkButton as well.
}
And now, if your UpdatePanel causes ConditionalUpdate, you can do something like this to make it work:
The Markup:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>..
<EditItemTemplate>
...
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" OnClick="Cause_PostBack"CommandName="Update">Update</asp:LinkButton>
...
</EditItemTemplate>
..</ContentTemplate>
</asp:UpdatePanel>
CodeBehind:
//call this function as the OnClick Event Handler for the Controls you want to register as
//triggers.
protected void Cause_PostBack()
{
UpdatePanel1.Update();
}
Otherwise, if your situation allows it(as mine does), just set the UpdatePanel's UpdateMode="Always"
This is old, but was trying to solve another problem and ran into this. This wasn't my problem, but here's an alternative for anyone new who runs into this as well.
You stated your problem as:
Since the InsertButton and the UpdateButton reside inside the Formview, I cannot directly access their ID's through markup
You actually can access their ID's through markup to use as the ControlID in the PostBackTrigger. You just have to use the button's name that is created in the page html mark-up as the ControlID. You can find the name created by viewing the page source when you're viewing the page in the browser. It typically is the name of the FormView + $ + name of the button.
For example, let's say you have a FormView named "FormView1" that contains an Insert button which you gave the ID of "btnInsert" during design. If you open up your page in the browser to view it live and then view the page's source, you'll notice that the html mark-up of the button will actually be given the name "FormView1$btnInsert".
Use that name as the ControlID in your PostBackTrigger and your update panel will work.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="FormView1$btnInsert" />
</Triggers>
<ContentTemplate>....</ContentTemplate>
</asp:UpdatePanel>

Resources