Click here to Skip to main content
15,883,971 members
Articles / Web Development / XHTML

FileUpload with Master Page, Ajax Update Panel, FormView and Object Data Source

Rate me:
Please Sign up or sign in to vote.
3.82/5 (8 votes)
2 Mar 2009GPL32 min read 109.9K   1.6K   32   12
FileUpload with Master Page, Ajax Update Panel, FormView and Object Data Source
Image 1

Introduction

It’s my first article for ASP.NET. Generally I write code in the network field with C#.NET but since a few days, I was working in Web development and facing various problems. I'm writing this article after finding a solution to a problem that I faced in my project. You can see my blog here.

Background

A few days ago, I was trying to make a file upload module in my project. It is an Ajax based project with Master-Content page. I was using Form View control to insert-update & show data, and for ADO.NET using Object Data Source. The problem was as follows:

  1. Ajax does not support File upload control (because file upload control needs complete post back event), and Ajax code is in the Master page, but file upload control is in the content page within form view.
  2. Form view control uses object data source to insert data, here I can't bind with file upload control with object data source because in file upload control does not have property to bind.

To solve it, I posted my question in the ASP.NET forum and also searched a lot, but I did not find any solution.

Using the Code

To solve my first problem, I've taken the help of others from the ASP.NET site. To upload a file in Ajax, it needs to register as post back control. And to register it, just write code as shown below:

C#
ScriptManager.GetCurrent(this).RegisterPostBackControl(Control Id);    

But the problem is in the second point. How can we bind Object Data Source property with File upload control. I've not got any property to bind. So I've do it in another way. In page load event has assigned file upload control’s file name with a text box and that text box has binded with object data source. Here all controls like file upload control, button, text box are in form view control. So I've written code like:

C#
if (Page.IsPostBack)
        {
            if (FormView1.CurrentMode == FormViewMode.Insert)
            {
                FileUpload objFU = (FileUpload)FormView1.FindControl("FileUpload1");
                TextBox objTB = (TextBox)FormView1.FindControl("TextBox1");
                if (objFU.HasFile)
                {
                    objTB.Text = objFU.FileName;
                    objFU.SaveAs(Server.MapPath(".") + "/" + objFU.FileName);
                }
            }
        }

Now the problem has been solved.

In that solution, I'm not describing about how you can access database in SQL Server. You just need to create a table with that SQL script:

SQL
CREATE TABLE [testFile]([fileName] [varchar](50) ,[other] [nchar](10))         

Here it also has one section to see that Ajax facility has put get server time. So the entire code is in ASP.NET for the Master page:

ASP.NET
<%@ 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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" ></asp:ScriptManager>
        <asp:UpdatePanel ID="upPnl" runat="server">
        <ContentTemplate>
    <div>
    
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        </asp:contentplaceholder>
    </div>
    </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>        

And for content page:

ASP.NET
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" 
	AutoEventWireup="true" CodeFile="Default.aspx.cs" 
	Inherits="Default" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
        
        <div style="border:Solid 1px; width:350px; text-align:center; 
			padding:10px 5px 10px 5 px; ">
        Non Ajax Area For File Upload
            <asp:FormView ID="FormView1" runat="server" 
		DataSourceID="ObjectDataSource1" DefaultMode="Insert">
                <InsertItemTemplate>
                    <asp:FileUpload ID="FileUpload1" runat="server"  />
                    <asp:Button ID="Button1" runat="server" 
			CommandName="Insert" Text="Save" />
                    <br />
                    <asp:TextBox ID="TextBox1" Visible="false" 
			runat="server" Text='<%# Bind("FileName") %>'></asp:TextBox>
                    <br />
                    Other Text: <asp:TextBox ID="TextBox2" 
			runat="server" Text='<%# Bind("Other") %>'></asp:TextBox>
                </InsertItemTemplate>
            </asp:FormView>
            <asp:ObjectDataSource ID="ObjectDataSource1" 
			runat="server" InsertMethod="Insert"
                SelectMethod="Select" TypeName="BL" DataObjectTypeName="BL">
            </asp:ObjectDataSource>
        </div>
        
        <br />
        <div style="border:solid 1px; width:350px; 
			text-align:center;padding:10px 5px 10px 5 px; ">
        Ajax Area To Get Server Time
        <br />
        <asp:Button ID="Button2" runat="server" 
		Text="Get Server Time" OnClick="Button2_Click" /><br />
        Server Time Is: 
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </div>     
   
</asp:Content>       

And in business logic, the code is:

C#
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DbClass;
/// <summary>
/// Summary description for BL
/// </summary>
public class BL
{
    DbClass.SqlDbAccess objDB = new SqlDbAccess
				(ConfigurationManager.AppSettings["ConnStr"]);
    public BL()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    private string _fileName;
    private string _other;
    public string FileName
    {
        get { return _fileName; }
        set { _fileName = value; }
    }

    public string Other
    {
        get { return _other; }
        set { _other = value; }
    }

    public void Insert(BL objectBl)
    {
        objDB.ExecuteNonQuery("INSERT INTO 
		[test].[dbo].[testFile]([FileName],[Other])VALUES
		('"+objectBl.FileName+"','"+objectBl.Other+"')");

    }
    public DataTable  Select()
    {
        return objDB.GetDataTable("SELECT FileName,Other FROM [test].[dbo].[testFile]");
    }
}

In code behind of content page:

C#
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager.GetCurrent(this).RegisterPostBackControl(FormView1);

        if (Page.IsPostBack)
        {
            if (FormView1.CurrentMode == FormViewMode.Insert)
            {
                FileUpload objFU = (FileUpload)FormView1.FindControl("FileUpload1");
                TextBox objTB = (TextBox)FormView1.FindControl("TextBox1");
                if (objFU.HasFile)
                {
                    objTB.Text = objFU.FileName;
                    objFU.SaveAs(Server.MapPath(".") + "/" + objFU.FileName);
                }
            }
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Label1.Text = DateTime.Now.ToString();
    }
}       

The entire project has been attached with this article, please take a look at it for more details. 

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionhow to upload image into a database Pin
Member 102458955-May-15 4:15
Member 102458955-May-15 4:15 
GeneralMy vote of 5 Pin
Pavel Yermalovich7-Oct-10 23:58
Pavel Yermalovich7-Oct-10 23:58 
GeneralGood Article Pin
Smart_Boy10-Feb-10 23:15
Smart_Boy10-Feb-10 23:15 
Generalsmall question Pin
silu4428-Dec-09 22:29
silu4428-Dec-09 22:29 
GeneralYou Save My Life Pin
Mc.Carvalho1-Jul-09 8:01
Mc.Carvalho1-Jul-09 8:01 
GeneralEnglish... Pin
Ryan Barrett23-Mar-09 4:02
Ryan Barrett23-Mar-09 4:02 
GeneralSmall comment Pin
kubal50038-Oct-08 15:08
kubal50038-Oct-08 15:08 
GeneralRe: Small comment Pin
kraftspl2-Mar-09 8:43
kraftspl2-Mar-09 8:43 
RantPathetic Pin
mitchtaylorh13-Sep-08 9:49
mitchtaylorh13-Sep-08 9:49 
GeneralFile Upload with AJAX Masterpage Pin
Prasath_S23-Jul-08 22:58
Prasath_S23-Jul-08 22:58 
GeneralRe: File Upload with AJAX Masterpage Pin
Alomgir Miah A3-Mar-09 10:24
Alomgir Miah A3-Mar-09 10:24 
GeneralRe: File Upload with AJAX Masterpage Pin
Smart_Boy10-Feb-10 22:30
Smart_Boy10-Feb-10 22:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.