Postback only Web Server Control - c#

I have created a Composite Web Server Control which displays Image Thumbnails after a user selects files. This control uses
DataList ( to show Image Thumbnails)
RadUploadAsync ( To upload files)
For making the postback on RadUploadAsync I am making a false postback on a label.
function OnClientFileUploaded(sender, args) {
var contentType = args.get_fileInfo().ContentType;
//alert(contentType);
__doPostBack('lblSelectImage', 'radListView');
}
However when i add this control in a web page, this creates a complete postback of the page. Can someone tell me on how to avoid complete postback and keep it limited to Web Server Control only? Please note that this web server control is present inside
<asp:UpdatePanel ID="updatePanel1" runat="server">
<ContentTemplate>
<cc1:ImageControl ID="ImageControl1" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>

Postbacks can be avoided by creating HTML Handler. For Rad Controls, telerik has given nice sample here.
http://demos.telerik.com/aspnet-ajax/asyncupload/examples/imageuploader/defaultcs.aspx

Related

To get value from user control using ajax

I have datalist in field.ascx and i have a label and textbox in fields.ascx and i am binding textbox and label dynamically in datalist and display in webform.aspx.Now i want to get label text and textbox value in webform.aspx when clicking a button in webform.aspx using ajax.
field.ascx:
<asp:DataList ID="dtlist" runat="server" RepeatColumns="4" CellPadding="5" EnableViewState="True">
<ItemTemplate>
<data:Value ID="test" runat="server" />
<ItemTemplate>
</asp:DataList>
Fields.ascx:
<asp:Label ID="lbl" runat="server" />
<asp:TextBox id="tb4" runat="server" />
Webform.aspx
<button onclick="myFunction()">Click me</button>
[WebMethod]
public static string LoadUserControl()
{
using (Page page = new Page())
{
HtmlForm form = new HtmlForm();
UserControl userControl = (UserControl)page.LoadControl("UserControls/field.ascx");
form.Controls.Add(userControl);
using (StringWriter writer = new StringWriter())
{
page.Controls.Add(form);
HttpContext.Current.Server.Execute(page, writer, false);
return writer.ToString();
}
}
}
You are destroying the values in the user control within the following line of your ASP.NET AJAX page method:
using (Page page = new Page())
In reality, you don't have access to the Page object at all within an ASP.NET AJAX page method, because it is static and does not at all interact with the ASP.NET Page Lifecycle.
If you are only going to have one instance of your user control, then you could use jQuery selectors in your myFunction JavaScript function to pull out the values for the Label and TextBox controls (be aware of the container naming that ASP.NET uses for master pages, and the control hierarchy). You can then build up an object literal to pass to the ASP.NET AJAX Page Method via the jQuery .ajax() function.
If you are going to have multiple instances of the user control on your page, then you will be better off using a server-side solution, coupled with the ASP.NET UpdatePanel control to give the illusion of asynchronous calls to the server (read: less screen flickering, because of only a partial postback). In this case, you can have public properties of the values you want to pull out of the user control and your server-side code will have references to each of the user control instances by ID.
So bottom line is that if you do not need to actually use a client-side JavaScript function to make a call to the server, then just use the server-side button click handler to do the logic of getting values from the server-side controls. The water quickly gets muddied when trying to get values out of server-side controls that could have multiple instances.

UpdateProgress and trigger section not working in Update panel while implement file upload control asynchronously

I am trying to upload image files with asp.net file upload control inside an update panel. I want to process UpdateProgress to show a progress bar image indicating a progress as well along with the file upload.
Case 1: When I remove the trigger section and use UpdateProgress section, the progress procedure is working fine but the file upload control fails to upload my files. [The page doesnot reload]
Case 2: When I use trigger section and remove UpdateProgress section, the file gets uploaded but the page gets reloaded.
Expected: What I really want is a fine file upload process that includes UpdateProgress to show progress image and strictly with no page loads.
What I have been to is:
.aspx section
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdateProgress ID="loading" runat="server">
<ProgressTemplate>
<asp:Image ID="Image1" CssClass="loadingGeneral" ImageUrl="../Images/loading(1).gif" AlternateText="Processing" runat="server" />
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:FileUpload ID="fileUploadForAlbum" multiple="true" CssClass="buttonclass" runat="server" ToolTip="Click to browse image." />
<asp:Button ID="btn_uploadAlbum" runat="server" class="buttonclass" OnClick="btnUploadAlbum_Click" Text="Upload Slider" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btn_uploadAlbum" />
</Triggers>
</asp:UpdatePanel>
.aspx.cs section
File upload code section is fine and I have used following to implement progress bar.
protected void btnUploadAlbum_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
do something.........
}
Thanks in advance. Any help is appreciated.
There are some interesting facts to know about FileUpload control.
1.) file upload control doesn't work with asynchronous postback. It always needs a postback to work properly. This is the reason why you see full page postbacks.
2.) AsyncPostbackTrigger will not help here to prevent postback.
MSDN says clearly that:
The FileUpload control is designed to be used only in postback scenarios
and not in asynchronous postback scenarios during partial-page rendering.
When you use a FileUpload control inside an UpdatePanel control, the file must
be uploaded by using a control that is a PostBackTrigger object for the panel
This makes to infer our third point:
3.) We need to use PostBackTrigger to make the FileUpload control work with UpdatePanel, which is then going to have a full page postback.
Your Question:
What I really want is a fine file upload process that includes UpdateProgress
to show progress image and strictly with no page loads
One of the good answer to this is to use the AsyncFileUpload control.
Features of this control:
It works within the Update Panel
You can show the loading image while file uploading is in progress, using ThrobberID property.
It uploads the file without any postback
It provides Client Side and Server side events
There are different coloring options for showing file upload. As for example, it shows green color if upload is successful: Use the CompleteBackColor property, otherwise it shows red if there is unsuccessful upload, using ErrorBackColor property.
On your .aspx page, place a script manager and register the Ajax control toolkit DLL.
<%# Register Assembly="AjaxControlToolkit"
Namespace="AjaxControlToolkit" TagPrefix="ajaxasyncFU" %>
Now place the AsyncFileUpload control:
<ajaxasyncFU:AsyncFileUpload ID="AsyncFileUpload1" runat="server"
OnClientUploadError="uploadError" OnClientUploadStarted="StartUpload"
OnClientUploadComplete="UploadComplete"
CompleteBackColor="Lime" UploaderStyle="Modern"
ErrorBackColor="Red" ThrobberID="Throbber"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete"
UploadingBackColor="#66CCFF" />
There are 3 client events you can use: OnClientUploadError, OnClientUploadStarted, and OnClientUploadComplete
And one Server side event: onuploadedcomplete, which is called in asynchronous manner thus avoiding full page postback.
In this server event usually we save the file:
protected void AsyncFileUpload1_UploadedComplete
(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if (AsyncFileUpload1.HasFile)
{
string strPath = MapPath("~/MyImages/") + Path.GetFileName(e.filename);
AsyncFileUpload1.SaveAs(strPath);
}
}
Check these 2 links: Link1 , Link2 for further reading.

Auto Fill Textbox in ASP.NET depending on the text typed in another textbox

how to fill textbox in asp.net while i am typing in another text
.. changes in one textbox will affect in another textbox auto.. and without refreshing my page.
Ok, try this. You will need the AJAX Control Toolkit. So read the article Installing AJAX Control Toolkit 4 in Visual Studio 2010 to see how to install it in Visual Studio.
Then you need to add a ScriptManager to your ASPX page. You will need to add the following code:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
What you then need to do, is add an UpdatePanel to your page. Inside this update panel, you need to place the textbox. This means that only the controls inside the update panel will refresh, and not the whole page. To do this, add the following code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!--Add your Textbox Control to update here: Textbox1-->
<asp:TextBox ID="Textbox1" runat="server" ReadOnly="True"></asp:TextBox>
<asp:TextBox ID="Textbox2" runat="server" ReadOnly="True" ontextchanged="Textbox2_TextChanged"></asp:TextBox>
</ContentTemplate>
<Triggers>
<!--This is the textbox you will be typing text into: TextBox2-->
<asp:AsyncPostBackTrigger ControlID="Textbox2" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
The Trigger tells your page which control on the form needs to initiate the postback. Now in your .cs file, you need to add the event handler for the Textbox2 TextChanged event. Add the following code:
protected void Textbox2_TextChanged(object sender, EventArgs e)
{
// Set the text of textbox1 = textbox2
}
I hope that this helps.
No need for AJAX. JQuery is enough. The code will do it
$('#text1').bind('keyup', function(){
$('#text2').val($('#text1').val());
});
Assuming
text1 id of box writing into.
text2 textbox that text gets copied to
in .Net you will have to use client id to get the correct id so it may look like this
$('<%=text1.ClientID%>').bind('keyup', function(){
$('<%=text2.ClientID%>').val($('#text1').val());
});
Oh and wrap it up in $(document).ready as per standard. And of coures you need to include the JQuery library to your page.
No posting back or page refreshes at all. It's your lightest solution and easy to implement.
You will need to use Javascript to accomplish this. ASP.Net code runs on the server side, which means it cannot affect the page without a postback happening first. Read up on the OnTextChanged event and how to hook into it with javascript. There is a javascript library called jQuery which makes everything easier, though it isn't strictly necessary.
Use JQuery. You may need to make an AJAX call to the server if you are relying on a datasource such as a database to autofil this field.

Upload a file to server automatically inside a update panel in asp.net website

I have a file upload inside the update panel, and an upload button that uploads the file to the server. Is it possible to upload the file without clicking the upload button? I want to remove the upload button and upload the file as soon as the file is selected from the user's machine. Or, have a 4 second timer, then call the upload_click to check if the fileupload has a file or not. How can I do it without a button inside update panel?
<asp:UpdatePanel ID="UP_DDL" runat="server" UpdateMode="Always" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Upload" OnClick="Upload_Click" runat="server" Text="Upload" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Upload"/>
</Triggers>
</asp:UpdatePanel>
protected void Upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(Server.MapPath("~/Bulk Upload"), FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
}
I am sure you can use any of the events on the HTML INPUT File element to fire up a full post back, which is all you need in order to upload the file automatically.
Google, at least on the standard interface, uses some sort of Flash plugin to accomplish what you want.
There might be some other jQuery plugins that provide this functionality out of the box. This one, for example, seems to do it.
You would need to mimic the click with some client-side code, such as using submit from Javascript - and this is not supported by at least one notable browser, I believe, IE.
Otherwise, you could use jQuery ajax calls to static web methods which do uploads on the fly, behind the scenes, when the value of the file upload control have changed.
You can hide Upload button with display:none inline style and add following code to Page_PreRender method:
FileUpload1.Attributes["onchange"] = ClientScript.GetPostBackClientHyperlink(Upload, "");
Or consider to use AsyncFileUpload control from AjaxControlToolkit

Showing errors in updatepanel after processing a CSV file

I have a csv importroutine which imports my CSV values into Sitecore. After this proces is done i want to show the errors in an asp:literal. This is not working, and I think this is because i need an updatepanel for this in order to be able to update text after the first postback (the csv upload / import).
I made this:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
and coded this:
string melding = string.Format("Er zijn {0} objecten geïmporteerd.{1}", nrOfItemsImported, errors);
ViewState["Melding"] = melding;
And i have a button. On the onclick of this button I have:
Literal literal = new Literal();
literal.Text = (string)ViewState["Melding"];
literal.ID = DateTime.Now.Ticks.ToString();
UpdatePanel1.ContentTemplateContainer.Controls.Add(literal);
PlaceHolder1.Controls.Add(literal);
When i now press the button i want to update the panel so that it will show my Literal with the errormsg on it. This however isn't happening. How can this be? I'm guessing it has something to do with my viewstate, i don't see keys on the viewstate after I press the button...
#Update:
I found the problem. I was storing information in a session, however the data for the key i was storing the information in was too large. This made the Session key empty. I was posting an empty string into my literal and therefore no information was shown. I am now looking for a better way to store my data and make it show in my updatepanel. I have tried Viewstate / Session / Cookies and none of it would work the way i wanted. When I am using a viewstate I am not able to store information. The viewstate (debugmode) shows count 0 and 0 keys ... Hope someone knows a good way to make sure that my errorstring (476kb) gets stored somewhere where i can easily post it to my updatepanel's literal.
If you are using a FileUpload control, then you cannot use the UpdatePanel to asynchronously update the panel. The file upload is a synchronous event, so you'll need to update the Literal control on the page after the upload completed during the next Page_Load event.
In your code, have you tried UpdatePanel1.Update();? Even though you have added a control, you still will need to "trigger" the update to the update panel.
See here for a possible similar issue: StackOverflow
I tried this code and on click of button I am able to get the literal text on web page. Can you provide with some more details .

Categories