Click here to Skip to main content
6,822,613 members and growing! (23,668 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Samples     Intermediate License: The GNU General Public License (GPL)

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

By SumanBiswas

FileUpload with Master Page, Ajax Update Panel, FormView and Object Data Source
C#, HTML, XHTML, ASP, ASP.NET, WebForms, Ajax
Revision:3 (See All)
Posted:23 May 2008
Updated:2 Mar 2009
Views:31,991
Bookmarked:23 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
5 votes for this article.
Popularity: 2.30 Rating: 3.29 out of 5
1 vote, 20.0%
1
1 vote, 20.0%
2

3
1 vote, 20.0%
4
2 votes, 40.0%
5

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 (GPL)

About the Author

SumanBiswas


Member
My own site:
www.sumanbiswas.xm.com
Occupation: Web Developer
Location: India India

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 8 of 8 (Total in Forum: 8) (Refresh)FirstPrevNext
Generalsmall question Pinmembersilu4423:29 28 Dec '09  
GeneralYou Save My Life PinmemberMc.Carvalho9:01 1 Jul '09  
GeneralEnglish... PinmemberRyan Barrett5:02 23 Mar '09  
GeneralSmall comment Pinmemberkubal500316:08 8 Oct '08  
GeneralRe: Small comment Pinmemberkraftspl9:43 2 Mar '09  
RantPathetic Pinmembermitchtaylorh10:49 13 Sep '08  
GeneralFile Upload with AJAX Masterpage PinmemberPrasath_S23:58 23 Jul '08  
GeneralRe: File Upload with AJAX Masterpage PinmemberAlomgir Miah Abdul11:24 3 Mar '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 2 Mar 2009
Editor: Deeksha Shenoy
Copyright 2008 by SumanBiswas
Everything else Copyright © CodeProject, 1999-2010
Web19 | Advertise on the Code Project