I use ajaxToolkit:AjaxFileUpload. It works when the user clicked in the start upload button. I want to change it so when the file is selected or drag-and-dropped, the uploader starts uploading automatically. What should I do? my code is:
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUploader" OnUploadComplete="AjaxFileUploader_UploadComplete" runat="server" />
protected void AjaxFileUploader_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
AjaxFileUploader.SaveAs(MapPath("~/UploadedFiles/" + e.FileName));
}
Let your Upload component to use the class "FileAttachmentUpload"
then use the below jQuery.
$(".FileAttachmentUpload").change(function () {
$(".FileAttachmentUpload .ajax__fileupload_uploadbutton").click();
});
$(".ajax__fileupload_dropzone").on('drop', function () {
$(".ajax__fileupload_uploadbutton").click();
});
Related
I'm doing an employee registration were there is an image that the user can preview the picture they choose. So my problem is, when I tried to preview the selected image, the filename in the fileupload is gone..
the "save-14-copy.png" is the filename of the picture.
So next step is to preview the image..
So as you can see the "save-14-copy.png" is already gone after hitting the button preview.
How can I retain the filename so I will not get an error when saving it.?
Code for design:
<asp:Button runat="server" ID="Button1" Text="PREVIEW" CssClass="button-green" OnClick="Button1_Click"/>
Javascript:
<script type="text/javascript">
function ImagePreview(Imagepath) {
if (Imagepath.files && Imagepath.files[0]) {
var Filerdr = new FileReader();
Filerdr.onload = function (e) {
document.getElementById("<%= hfImage.ClientID %>").value = e.target.result;
}
Filerdr.readAsDataURL(Imagepath.files[0]);
}
}
</script>
Codebehind:
protected void Button1_Click(object sender, EventArgs e)
{
EmpImage.ImageUrl = hfImage.Value;
}
i think you should save the file at preview-click and handle the filename there
protected void Button1_Click(object sender, EventArgs e)
{
hfImagename.Value = fuFile.PostedFile.FileName;
fuFile.PostedFile.SaveAs(#"C:\foo\" +fuFile.PostedFile.FileName);
}
Your Preview button is actually causing a post back to the server. The way you have it setup now, the Preview button would be more appropriately called Upload.
You are using the FileReader object in order to read the file from the user's local file system and showing it in the image before upload. All of that should take place only in the client. Once the user is happy with the selected picture, he can upload the picture to the server.
Here is a very simple sample that should get you started.
.aspx file
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="preview" runat="server" ImageUrl="~/Images/NotSelectedYet.jpg" />
<br />
<asp:FileUpload ID="pictureOfMe" runat="server" />
<input type="button" value="Preview" onclick="Preview();" />
<br />
<asp:Button ID="Upload" runat="server" Text="Upload file to server" OnClick="Upload_Clicked" />
</div>
</form>
<script type="text/javascript">
function Preview() {
var fileInput = document.getElementById('<%= pictureOfMe.ClientID %>');
var filePreview = document.getElementById('<%= preview.ClientID %>');
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function (e) {
filePreview.src = reader.result;
}
reader.readAsDataURL(file);
}
else {
alert('Not an image file!');
}
}
</script>
</body>
Here we have an image that is showing a default picture when first loaded. Then we have a file upload control that lets the user select a picture to upload. And we have an html input button that the user clicks on to preview the selected picture. When this button is clicked, it runs javascript code that uses the FileReader to load the file an show it in the image. Note that the preview button will not cause a post back to the server.
And we also have a server button that will post the page (including the selected picture) to the server with a server event handler declared.
.aspx.cs file
public partial class TestImagePreviewAndUpload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Upload_Clicked(object sender, EventArgs e)
{
if(pictureOfMe.PostedFile.FileName != string.Empty) {
byte[] uploadedBytes = pictureOfMe.FileBytes;
//save uploaded picture here
}
}
}
Here, in the Upload_Clicked method we check if a file was uploaded and gets the file content as a byte[]. Actuelly storing the file is left as an exercise...
Note: Sample javascript (with some modifications) from here
i have created "ButtonClick" function in ASP.NET as following:
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" CausesValidation="true" onclick="btnLogin_Click"/>
i want to know, is it possible to call a javascript function before and after calling asp.net button click function...???
Thanks.
Yes it's possible, here is quick example:
Java script function to call.
<script type="text/javascript">
function clientValidate() {
alert("execute before");
return true;
}
function executeAfter() {
alert("execute after");
}
</script>
Here is snapshoot for button
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="clientValidate()" onclick="btnLogin_Click"/>
Notice property onClientClick="clientValidate()", it will be trigger script before button click on the server.
On the server side:
protected void btnLogin_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "none", "<script>executeAfter();</script>", false);
}
Notice executeAfter();, it will trigger javascript execution after server event.
Don't forget to place <asp:ScriptManager runat="server"></asp:ScriptManager> in your aspx file.
Hope it help
put this on your page and make sure you have a scriptmanager. these codes will handle your pre & post postbacks.
var prm, postBackElement;
if (typeof Sys != "undefined") {
prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
}
function InitializeRequest(sender, e) {
postBackElement = e.get_postBackElement();
if (postBackElement.id == "btnLogin") {
// before click codes
}
}
function EndRequest(sender, e) {
if (postBackElement.id == "btnLogin") {
// after click codes
}
}
Before:
<script type="text/javascript">
function executeBefore() {
alert("execute before");
}
</script>
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="executeBefore()" onclick="btnLogin_Click"/>
After:
<script type="text/javascript">
function executeAfter() {
alert("execute after ");
}
</script>
Add this code to your server side event:
Page.ClientScript.RegisterStartupScript(GetType(), "none", "<script>executeAfter();</script>", false);
If you don't have a master page, or are not using ajax, there is no need to add ScriptManager.
You can call Java scrip function before server side click using OnClientClick():
aspx(design)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function Test() {
alert('client click');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button Text="btn" runat="server" ID="btn"
OnClick="btn_Click" OnClientClick="Test()" />
</div>
</form>
</body>
</html>
.cs
protected void btn_Click(object sender, EventArgs e)
{
Response.Write("Server Click");
}
First time you can call your javascript function in Button's OnClientClick event passing your function name.
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" CausesValidation="true" onclick="btnLogin_Click" OnClientClick="return functionNAME();"/>
Second time, in your button click event btnLogin_Click call js as follow
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "script", "<script type='text/javascript'>functionNA();</script>", false);
For calling it before, you could consider using onload function, like this example:
<body onload="myFunction()">
For calling it afterwards, just link the button to execute JS onClick?
I don't think I quite understand your intentions.
During the page_load, I disable the timer. When I pressed Button1, I enable the timer, but the page refreshes. Therefore, it never reaches the timer_tick1. I need to show a popup after a certain amount of time a button is clicked. How do I prevent the refresh from happening?
Alerts Class
public static class Alert
{
public static void Show(string message, Page page)
{
// replaces the quotations to follow the script syntax
// quotations are interpretated as \\' in script code
string cleanMessage = message.Replace("'", "\\'");
string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
// Gets the executing web page
Page tempPage = page;
// Checks if the handler is a Page and that the script isn't already on the page
if (tempPage != null & !tempPage.ClientScript.IsClientScriptBlockRegistered("alert"))
{
tempPage.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script); // this isn't working, but it works on a button click event.
}
}
}
Page Class
public partial class Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback) {
Timer1.Enabled = false;
Label2.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if page reloads
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{ // i added a breakpoint here. It doesn't even pass through.
Alert.Show("hehehehe", this); //PopUp Shows up.
Timer1.Enabled = false; //Cancels Timer
Label1.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if update panel reloads
}
protected void Button1_Click1(object sender, EventArgs e)
{
Timer1.Enabled = true; //Starts Timer. It seems to refresh the page.
}
}
script
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Test1" %>
<%# Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
function delayer() {
setTimeout (function () {ShowPopUp()}, 15000);
}
delayer();
</script>
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="1000" Enabled="true">
</asp:Timer>
<asp:Label ID="Label1" runat="server" Text="PanelNotRefreshedYet"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="ShowPopUp();" />
</form>
</body>
</html>
I think you're confused. Timer1 is a server side control. So it will fire on the server side, if you're still processing the page, that is, and will have no effect on the client side. By the time it fires in your code, the page has likely already rendered so you'll see no effect from that Timer1 object's Timer1_Tick event. Since the page has completed rendering, you can't inject new JavaScript, modify the page, or anything like that. Remember that web development is a disconnected thing. You send a request, you get a response. There are no events by nature of the web. There are libraries out there for triggering events and such but I think that's way beyond what you're trying to achieve.
For client side "timer" you need to use JavaScript setTimeout method, which you have verified as working and is the proper way for you to achieve the delay you're looking to implement.
setTimeout (function () {ShowPopUp()}, 15000);
If you still want to do it in your Alert class, then get rid of Timer1 and have your Alert class inject the timeout in JavaScript:
protected void Button1_Click1(object sender, EventArgs e)
{
Alert.Show("He heee", this);
}
And in Alert, change your script to:
string script = "<script type=\"text/javascript\">setTimeout(function() {alert('" + cleanMessage + "');}, 15000);</script>";
Your button is doing a postback, so yes the page will be refreshed and your Page_Load function will run again. You should test for this using the IsPostback property.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback) {
Timer1.Enabled = false;
Label2.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if page reloads
}
}
You might want to look at showing the alert using JavaScript on the page rather than running it server side tho.
<script type="text/javascript">
function showPopup()
{
alert("Hey, click something already");
}
function delayer() {
setTimeout (showPopUp, 15000);
}
delayer();
</script>
Just put your message like this. Probably easier if your logic is simple.
I want to start a process when i clicked the start button on webpage (asp.net site) now i want to set the label text to process started. and i want to set the label text to "Process Completed " when the process is ended. how to do this in asp.net and C#.
Thanks in advance.
You might want to consider using ASP.NET SignalR. Here's a summary of what it does:
ASP.NET SignalR is a new library for ASP.NET developers that makes it
incredibly simple to add real-time web functionality to your
applications. What is "real-time web" functionality? It's the
ability to have your server-side code push content to the connected
clients as it happens, in real-time.
The following is an example of simple web page with a button which starts Notepad.exe. Once the process is started, a label on the page shows process started. When the process exits (Notepad is closed), the label's updates to process exited.
So, first create an ASP.NET empty web application project (let's name it MyWebApplication) and get the Microsoft ASP.NET SignalR NuGet package. Add a web form to the project and name it Test. Add the following code to the Test.aspx file:
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="Test.aspx.cs" Inherits="MyWebApplication.Test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"
type="text/javascript"></script>
<script src="Scripts/jquery.signalR-1.0.1.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.client.addMessage = function (message) {
$('#label').text(message);
};
// Start the connection
$.connection.hub.start();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" />
<div>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Button runat="server" Text="Start Notepad.exe"
ID="button" OnClick="button_Click" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger
ControlID="button" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<span id="label"></span>
</div>
</form>
</body>
</html>
Add a new class file to your project and name it Chat. In Chat.cs you will have:
using Microsoft.AspNet.SignalR;
namespace MyWebApplication
{
public class Chat : Hub
{
public void Send(string message)
{
//Call the addMessage method on all clients
var c = GlobalHost.ConnectionManager.GetHubContext("Chat");
c.Clients.All.addMessage(message);
}
}
}
Add the following to the Test.aspx.cs file:
using System;
using System.Diagnostics;
using Microsoft.AspNet.SignalR;
namespace MyWebApplication
{
public partial class Test : System.Web.UI.Page
{
Chat chat = new Chat();
protected void Page_Load(object sender, EventArgs e)
{
}
void MyProcess_Exited(object sender, EventArgs e)
{
chat.Send("process exited");
}
protected void button_Click(object sender, EventArgs e)
{
Process MyProcess = new Process();
MyProcess.StartInfo = new ProcessStartInfo("notepad.exe");
MyProcess.EnableRaisingEvents = true;
MyProcess.Exited += MyProcess_Exited;
MyProcess.Start();
chat.Send("process started");
}
}
}
Add the Global.asax file:
using System;
using System.Web.Routing;
namespace MyWebApplication
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHubs();
}
}
}
Some things I haven't covered:
The label is updated on all connections.
I'm not verifying if the process is already running or not (but that shouldn't be very difficult to check).
Use javascript to do the callback. And on each stage; Initiated, Completed or Error; update a label in your html. This should be fairly simple if you look for some samples with jQuery AJAX.
jQuery AJAX POST example
If you dont want to use javascript...what you can do is to change label text first when button click event is fired.
lblLabel.text="process started"
and last line in button_click event should be like:
lblLable.text="process completed";
Add this in CodeBehind:
ScriptManager.RegisterStartupScript(this, GetType(), "Records Inserted Successfuly", "Showalert();", true);
JAVASCRIPT add this in source code (aspx):
function Showalert() {
alert('Records inserted Successfully!');
}
And do add using System.Web.UI;
OR
You can simply add a Label to the webform like this in aspx..
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
and in codebehind aspx.cs add ..
Labelname.Text = "whatever msg you wanna display."
I implemented the AsyncFileUpload control on a web page. This web page requires uploaded files to appear in a GridView.
The GridView contains the following columns: "File Name", "Confidential" Check Box, and a "Remove" button to remove the uploaded file.
Since the AsyncFileUpload postback does not do a full page postback, I need to "force" a postback on the OnClientUploadComplete event of the AsyncFileUpload control in order to render the gridview after uploading a file.
In the OnClientUploadCompleteEvent, I use javascript to call __doPostBack. In this postback, I only bind my GridView and display the file information (I don’t re-save the file).
The problem: On the AsyncFileUpload’s first “partial” postback, the file is successfully uploaded, as expected. On the second postback that I force with __doPostBack, the file is re-uploaded.
You can verify this by using Google Chrome, which displays the upload progress. The behaviour is as follows:
- After selecting the file, the progress increments from 0% to 100% and the file is uploaded.
- After this, the __doPostBack executes, and you can see the upload progress increment again from 0% to 100%.
How can I make sure the Gridview is properly populated, but that the file is not uploaded twice?
I attached a sample solution which contains the issue: https://www.yousendit.com/download/MzZFc2ZBNDRrYUN4dnc9PQ
There is a simpler solution
##t0x1n3Himself the solution u gave is very simple but does not work
surround the AsyncFileUpload with an update panel name it UpdatePanelAFU
then in the UpdatePanelAFU do as the following :
protected void AsyncFileUpload_UpdatePanelAFU(object sender,AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if (Request.Params.Get("__EVENTTARGET") != "UpdatePanelAFU")
return;
..... rest of the code
}
enjoy!
Maybe ugly, but works:
1)
Add a css-hidden asp:Button bellow the asp:AsyncFileUpload AsyncFileUpload1 control.
<asp:Button runat="server" ID="btnClick" Text="Update grid" style="display:none"/>
2)
On the Page_Load method, remove the if (Request.Params.Get("__EVENTTARGET") == "UploadPostback") and put its block in a simple else to the previous if.
3)
On the AsyncFileUpload1_UploadedComplete function, also remove the if (Request.Params.Get("__EVENTTARGET") != "UploadPostback") line, but leave intact everything that was inside it.
4)
Back to the aspx. Put a asp:UpdatePanel outside the grid GridView1.
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnClick" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="GridView1" ...
YOUR GRID CODE REMAINS THE SAME
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
5)
The last step is to change the AjaxUploadComplete client-side javascript function to make it trigger the postback.
Replace it with the following:
function AjaxUploadComplete() {
var btnClick = document.getElementById("btnClick");
btnClick.click();
}
Any file the user selects is uploaded only once.
All changes here are meant to be made in AjaxUpload.aspx & AjaxUpload.aspx.cs of your AjaxUpload.zip.
I believe #Veera had it right. UploadComplete was being called multiple times as the file was uploading. The following worked for me.
void AsyncFileUpload1_UploadedComplete(object sender, AsyncFileUploadEventArgs e) {
if (AsyncFileUpload1.IsUploading) return;
// rest of your upload code
}
I don't have access to your sample solution which contains the issue but i encounter a double postback too in my project with the AsyncFileUpload component.
I found a very simple workaround :
Just add:
private bool justUploaded = false;
Then:
void AsyncFileUpload1_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
{
if (justUploaded) return;
justUploaded = true;
// rest of your upload code
}
I find this a more elegant solution, found here: http://forums.asp.net/t/1951566.aspx?AsyncFileUpload+uploads+twice) but below is my altered fully working code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AsyncFileUpload Example</title>
<script type = "text/javascript">
function uploadComplete(sender) {
$get("<%=lblMesg.ClientID%>").innerHTML = "File Uploaded Successfully";
clearContents();
}
function uploadError(sender) {
$get("<%=lblMesg.ClientID%>").innerHTML = "File upload failed.";
clearContents();
}
function clearContents() {
var span = $get("<%=AsyncFileUpload1.ClientID%>");
var txts = span.getElementsByTagName("input");
for (var i = 0; i < txts.length; i++) {
if (txts[i].type == "text") {
txts[i].value = "";
}
if (txts[i].type == "file") {
txts[i].value = "";
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<cc1:AsyncFileUpload OnClientUploadError="uploadError"
OnClientUploadComplete="uploadComplete" runat="server"
ID="AsyncFileUpload1" Width="400px" UploaderStyle="Modern" EnableViewState = "false"
UploadingBackColor="#CCFFFF" ThrobberID="imgLoader" OnUploadedComplete = "FileUploadComplete"
/>
<asp:Image ID="imgLoader" runat="server" ImageUrl = "~/images/loader.gif" />
<br />
<asp:Label ID="lblMesg" runat="server" Text=""></asp:Label>
</form>
</body>
</html>
AsyncFileUpload has a property that named IsUploading.
when this property is set to false, a postback will happen.
you can check this property like this:
if(AsyncFileUpload1.IsUploading)
{
..... upload codes
}