Upload File using MasterPage without Form Submit (PostBack) using jQuery AJAX in ASP.Net

Last Reply 5 months ago By pandeyism

Posted 5 months ago

I got a solution from aspsnippets

Link: 

Upload File without Form Submit (PostBack) using jQuery AJAX in ASP.Net

I'm trying to implement this in my masterpage but it's not working as it should. It's displaying "undefined has been uploaded" as my success message. Please help.

Posted 5 months ago

Hi CodeLava,

Refer below sample.

HTML

MasterPage.master

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!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></title>
    <asp:ContentPlaceHolder ID="head" runat="server">        
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

CS.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("body").on("click", "[id*=btnUpload]", function () {
            $.ajax({
                url: 'HandlerCS.ashx',
                type: 'POST',
                data: new FormData($('form')[0]),
                cache: false,
                contentType: false,
                processData: false,
                success: function (file) {
                    $("[id*=fileProgress]").hide();
                    $("[id*=lblMessage]").html("<b>" + file.name + "</b> has been uploaded.");
                },
                xhr: function () {
                    var fileXhr = $.ajaxSettings.xhr();
                    if (fileXhr.upload) {
                        $("progress").show();
                        fileXhr.upload.addEventListener("progress", function (e) {
                            if (e.lengthComputable) {
                                $("[id*=fileProgress]").attr({
                                    value: e.loaded,
                                    max: e.total
                                });
                            }
                        }, false);
                    }
                    return fileXhr;
                }
            });
        });
    </script>
    <input type="file" name="postedFile" />
    <input type="button" id="btnUpload" value="Upload" />
    <progress id="fileProgress" style="display: none"></progress>
    <hr />
    <span id="lblMessage" style="color: Green"></span>
</asp:Content>

Code

CS

HandlerCS.ashx

<%@ WebHandler Language="C#" Class="HandlerCS" %>

using System;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;

public class HandlerCS : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        //Check if Request is to Upload the File.
        if (context.Request.Files.Count > 0)
        {
            //Fetch the Uploaded File.
            HttpPostedFile postedFile = context.Request.Files[0];
            
            //Set the Folder Path.
            string folderPath = context.Server.MapPath("~/Uploads/");

            //Set the File Name.
            string fileName = Path.GetFileName(postedFile.FileName);
            
            //Save the File in Folder.
            postedFile.SaveAs(folderPath + fileName);

            //Send File details in a JSON Response.
            string json = new JavaScriptSerializer().Serialize(
                new
                {
                    name = fileName
                });
            context.Response.StatusCode = (int)HttpStatusCode.OK;
            context.Response.ContentType = "text/json";
            context.Response.Write(json);
            context.Response.End();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

VB

HandlerVB.ashx

<%@ WebHandler Language="VB" Class="HandlerVB" %>

Imports System
Imports System.IO
Imports System.Net
Imports System.Web
Imports System.Web.Script.Serialization

Public Class HandlerVB : Implements IHttpHandler
    
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        'Check if Request is to Upload the File.
        If context.Request.Files.Count > 0 Then
            
            'Fetch the Uploaded File.
             Dim postedFile As HttpPostedFile = context.Request.Files(0)
            
            'Set the Folder Path.
            Dim folderPath As String = context.Server.MapPath("~/Uploads/")

            'Set the File Name.
            Dim fileName As String = Path.GetFileName(postedFile.FileName)
            
            'Save the File in Folder.
            postedFile.SaveAs(folderPath + fileName)
            
            'Send File details in a JSON Response.
            Dim json As String = New JavaScriptSerializer().Serialize(New With {
                .name = fileName
            })
            context.Response.StatusCode = CInt(HttpStatusCode.OK)
            context.Response.ContentType = "text/json"
            context.Response.Write(json)
            context.Response.End()
        End If
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

Screenshot