Click here to Skip to main content
Click here to Skip to main content

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

By , 2 Mar 2009
 

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:

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:

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:

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:

<%@ 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:

<%@ 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:

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:

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)

About the Author

SumanBiswas
Web Developer
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberPavel Yermalovich7 Oct '10 - 23:58 
It was quite usefull to solve my issue
GeneralGood ArticlememberSmart_Boy10 Feb '10 - 23:15 
Thanks, it help me a lot.
Regards,
Smart Boy
Mumbai,
(INDIA)

Generalsmall questionmembersilu4428 Dec '09 - 22:29 
i have a formview default mode is insert , there is 5 fields
---------
id
title
date
videofile
comment
----------------
asp.net 3.5 C# or VB
 
first this is intranet web app so i don't want to upload i just want to take the path
simple ( i want to bind only the file path to the videofile field
 
i want to browse for a file in my (C:\video\.....) .avi or any other video ext - then save the Path into database i don't want to upload it i just want to save the path (that mean i want to use fileupload control to get the path and bind it to (videofile field)
 
then in the grid-view i want to be able to click on the file path to play it or download it
 

GeneralYou Save My LifememberMc.Carvalho1 Jul '09 - 8:01 
Excelente Post my Friend.
 
I'm find is solution per two days.
GeneralEnglish...memberRyan Barrett23 Mar '09 - 4:02 
Nice post Suman, helped my evaluation of ajax.net. I've re-written your post into better English, if you want me to email it to you then drop me a line on ryan A seldonplan.com and I'll email it to you. Then we can delete this message Wink | ;)
GeneralSmall commentmemberkubal50038 Oct '08 - 15:08 
Unfortunately I wasn't able to understand this article. Code samples helped a bit, but the language is terrible. Frown | :(
 
Laziness is the programmers best friend.

GeneralRe: Small commentmemberkraftspl2 Mar '09 - 8:43 
A mediocre programmer needs ten minutes to understand this source. Comments are for wimps. Poke tongue | ;-P
RantPatheticmembermitchtaylorh13 Sep '08 - 9:49 
The english was so bad I couldn't understand what you were trying to say. If you can't write articles in English have someone else do it for you for god's sakes.
GeneralFile Upload with AJAX MasterpagememberPrasath_S23 Jul '08 - 22:58 
I am using Fileupload control in my masterpage for Ajax web application. But when i click the button to submit, file upload control text is missing. pls help me. its urgent.. :(
GeneralRe: File Upload with AJAX MasterpagememberAlomgir Miah Abdul3 Mar '09 - 10:24 
FileUpload control cannot be used with AJAX postbacks. If your asp:FileUpload is wrapped around UpdatePanel it will not work. You need a full postback for the FileUpload control to work.
 

Hope this helps.

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 2 Mar 2009
Article Copyright 2008 by SumanBiswas
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid