Yasserzaid’s Weblog

November 30, 2009

AJAX AsynFile Upload with File Extension Validation

Filed under: AJAX, ASP.Net — Tags: — yasserzaid @ 1:26 am

Hi

try this example to validate uploaded file extenstion using AJAX AsynFileUpload control

    <script type=”text/javascript”>       
        function uploadError(sender, args) {
            //Good practice to put try,catch block. it will avoid javascript error at window status.
            try
            {
                $get(“dvFileErrorInfo”).style.display=’block’;
                $get(“dvFileInfo”).style.display=’none’;
                $get(“<%=lblError.ClientID%>”).innerHTML = “File Not Uploaded” + args.get_errorMessage();
            }
            catch(e)
            {
                alert(e.message);
            }
        }
               
        function uploadComplete(sender, args) {
          try
          {
             var fileExtension=args.get_fileName();
             var gif =fileExtension.indexOf(‘.gif’);
             var png =fileExtension.indexOf(‘.png’);
             var jpg =fileExtension.indexOf(‘.jpg’);
             var jpeg =fileExtension.indexOf(‘.jpeg’);
            if( gif > 0 || png > 0 || jpg > 0 || jpeg > 0)
            {
                $get(“dvFileInfo”).style.display=’block’;
                $get(“dvFileErrorInfo”).style.display=’none’;
                $get(“<%=lblSuccess.ClientID%>”).innerHTML = “File Uploaded Successfully”;
            }
            else
            {
                $get(“dvFileErrorInfo”).style.display=’block’;
                $get(“<%=lblError.ClientID%>”).innerHTML = “Allowed File extension are {.gif,.png,.jpg,.jpeg} supported”;
                $get(“dvFileInfo”).style.display=’none’;
                return;
            }
          
          }
          catch(e)
          {
            alert(e.message);
          }     
        }
    </script>

    <div>
        <asp:ScriptManager runat=”Server” EnablePartialRendering=”true” ID=”ScriptManager1″ />
        <cc1:AsyncFileUpload ID=”afuUpload” OnClientUploadError=”uploadError” OnUploadedComplete=”afuUpload_UploadedComplete”
            OnUploadedFileError=”afuUpload_UploadedFileError” runat=”server” OnClientUploadComplete=”uploadComplete”
            Width=”400px” UploaderStyle=”Modern” UploadingBackColor=”#CCFFFF” ThrobberID=”myThrobber” />
        <asp:Label runat=”server” ID=”myThrobber” Style=”display: none;”>
                     <img align=”absmiddle” alt=”" src=”Images/uploading.gif” />
        </asp:Label>
        <div style=”border-style: solid; display: none; width: 350px” id=”dvFileInfo”>
            <asp:Label ID=”lblStatus” Font-Bold=”true” runat=”server” Text=”Status:-” /><asp:Label
                ID=”lblSuccess” ForeColor=”Green” runat=”server” /><br />
        </div>
        <div style=”border-style: solid; display: none; width: 350px” id=”dvFileErrorInfo”>
            <asp:Label ID=”lblErrorStatus” Font-Bold=”true” runat=”server” Text=”Status:-” /><asp:Label
                ID=”lblError” ForeColor=”Red” runat=”server” /><br />
        </div>
    </div>

and in code behind :-

    public void afuUpload_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
    {
        try
        {
            string savePath = MapPath(“~/Images/” + Path.GetFileName(e.filename));
            /*Validation for file extension*/
            bool gif =Path.GetExtension(e.filename).Contains(“.gif”);
            bool png =Path.GetExtension(e.filename).Contains(“.png”);
            bool jpg =Path.GetExtension(e.filename).Contains(“.jpg”);
            bool jpeg =Path.GetExtension(e.filename).Contains(“.jpeg”);
            if (gif || png || jpg || jpeg)
            {
                afuUpload.SaveAs(savePath);
            }
            else
            {
                return;
            }
          
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void afuUpload_UploadedFileError(object sender, AsyncFileUploadEventArgs e)
    {
        //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), “error”, “top.$get(\”" + lblErrorStatus.ClientID + “\”).innerHTML = ‘Error: ” + e.statusMessage + “‘;”, true);
    }

Hope this helps

Good Luck

October 27, 2009

AJAX Update Progress with Upload Image

Filed under: AJAX, ASP.Net — Tags: , — yasserzaid @ 6:38 pm

Hi

try this example to use AJAX Update Progress with Upload Image

1) Open VS 2005 and create new AJAX Website

2) Add new folder called “Upload” which will upload image on it

3)  Add new web page

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>Upload Image</title>
<style type=”text/css”>
.Progress
 {
   background-color:#CF4342;
   color:White;
   width:105px;
 }
 
.Progress img {
   vertical-align:middle;
   margin:2px;
 }

.progressBackgroundFilter {
  position:absolute;
  top:0px;
  bottom:0px;
  left:0px;
  right:0px;
  overflow:hidden;
  padding:0;
  margin:0;
  background-color:#000; 
  filter:alpha(opacity=50);
  opacity:0.5;
  z-index:1000;
}

.processMessage { 
  position:absolute; 
  top:30%; 
  left:43%;
  padding:10px;
  width:14%;
  z-index:1001;
  background-color:#fff;
}
</style>
<script language=”javascript” type=”text/javascript” >
//— to validate extension of fileupload control
function ValidateFile(source, args)    
{

try        
{              
var fileAndPath=document.getElementById(source.controltovalidate).value;       
var lastPathDelimiter=fileAndPath.lastIndexOf(“\\”);       
var fileNameOnly=fileAndPath.substring(lastPathDelimiter+1);              
var file_extDelimiter=fileNameOnly.lastIndexOf(“.”);       
var file_ext=fileNameOnly.substring(file_extDelimiter+1).toLowerCase();       
if(file_ext!=”jpg”)            
{            
args.IsValid = false;            
if(file_ext!=”gif”)              
args.IsValid = false;                 
if(file_ext!=”png”)                 
{                   
args.IsValid = false;                    
return;                 
}               
}       
}
catch(err)       
{         
txt=”There was an error on this page.\n\n”;         
txt+=”Error description: ” + err.description + “\n\n”;         
txt+=”Click OK to continue.\n\n”;         
txt+=document.getElementById(source.controltovalidate).value;         
alert(txt);         
}                   
args.IsValid = true;   
}   

//– to show UpdateProgress if FileUpload has File
function showWait()
{
    var isValid = Page_ClientValidate(“img”);
     if ( isValid == true )
     {
        if(document.getElementById(‘<%=fileUp.ClientID %>’).value != “”)
        {
            $get(‘UpdateProgress1′).style.display = ‘block’;

            return true;
        }
        else
        {
            alert(“SelectImage”);
            return false;
        }

      }  
}
</script>   
</head>
<body>
    <form id=”form1″ runat=”server”>
        <asp:ScriptManager ID=”ScriptManager1″ runat=”server” />
        <div>
            <asp:UpdatePanel ID=”UpdatePanel1″ runat=”server” UpdateMode=”Conditional”>
                <ContentTemplate>
        <asp:FileUpload ID=”fileUp” runat=”server”  />
        <asp:CustomValidator ID=”CustomValidator1″ runat=”server”
            ClientValidationFunction=”ValidateFile” ControlToValidate=”fileUp”
            Display=”Dynamic” ErrorMessage=”Select Image” ValidationGroup=”img” ></asp:CustomValidator>
            <br />
            <asp:Button ID=”btnAddFile” runat=”server” CausesValidation=”False”
                onclick=”btnAddFile_Click”  OnClientClick=”javascript:return showWait();”
                Text=”Add Image” ValidationGroup=”img” />
                </ContentTemplate>
                <Triggers>
                    <asp:PostBackTrigger ControlID=”btnAddFile” />
                </Triggers>
            </asp:UpdatePanel>
        </div>

        <asp:UpdateProgress ID=”UpdateProgress1″ runat=”server” AssociatedUpdatePanelID=”UpdatePanel1″  >
        <ProgressTemplate>
        <div id=”progressBackgroundFilter”></div>
        <div id=”processMessage” align=”center”>
        <asp:Label ID=”Label32″ runat=”server” Text=”Loading …” ></asp:Label><br /><br /><img src=”Images/5.gif” alt=”Loading” />
         </div>

    </ProgressTemplate>
    </asp:UpdateProgress>
    </form>
</body>
</html>

4) In code behind in Button Click Event:-

protected void btnAddFile_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(1000);
        //string filename = System.IO.Path.GetFileName(fileUp.FileName);
        //fileUp.SaveAs(Server.MapPath(“~/Upload/”) + filename);
        string File = Guid.NewGuid().ToString() + Path.GetExtension(fileUp.FileName);
        fileUp.SaveAs(Server.MapPath(“~/Upload/”) + File);
    }

Hope this helps

Good Luck

 

July 13, 2009

Use AJAX AutoComplete with Linq

Filed under: AJAX, Linq — yasserzaid @ 6:57 am

Hi

try this example to Use AJAX AutoComplete with Linq

<asp:ScriptManager ID=”SM1″ runat=”server” />

<asp:UpdatePanel ID=”UP1″ runat=”server”>
<ContentTemplate>
Enter Product Name:
<asp:TextBox ID=”txtName” runat=”server” AutoComplete=”Off” />
<cc1:AutoCompleteExtender ID=”txtName_AutoCompleteExtender” runat=”server”
TargetControlID=”txtName” MinimumPrefixLength=”1″ ServiceMethod=”GetProductNames”>
</cc1:AutoCompleteExtender>
</ContentTemplate>
</asp:UpdatePanel>
 
and in code behind :-

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

[System.Web.Services.WebMethod]
public static string[] GetProductNames(string prefixText, int count)
{
NorthwindDataContext db = new NorthwindDataContext();
return db.Products.Where(n => n.ProductName.StartsWith(prefixText)).OrderBy(n => n.ProductName).Select(n => n.ProductName).Take(count).ToArray();
}
}

Hope this helps

Good Luck

May 15, 2009

Hide AJAX Modal Popup with Esc Press

Filed under: AJAX — yasserzaid @ 11:35 pm

Hi

try this example to hide AJAX Modal Popup Extender when user press Esc Key

<%@ Page Language=”C#” %>

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”ajaxToolkit” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”head” runat=”server”>
    <title>Untitled Page</title>
    <style>
    .modalBackground {
        background-color:Gray;
        filter:alpha(opacity=70);
        opacity:0.7;
    }
    </style>
</head>
<body>
    <form id=”frm” runat=”server”>
        <asp:ScriptManager ID=”ScriptManager1″ runat=”server” />
        <script type=”text/javascript”>

        function pageLoad(sender, args){
            if(!args.get_isPartialLoad()){
                //  add our handler to the document’s
                //  keydown event
                $addHandler(document, “keydown”, onKeyDown);
            }
        }

        function onKeyDown(e){
            if(e && e.keyCode == Sys.UI.Key.esc){
                // if the key pressed is the escape key, dismiss the dialog
                $find(‘mdlPopupExtender’).hide();
            }
        }
       
        </script>

        <div style=”font-family:Tahoma; font-size:smaller”>
            <p style=”background-color:AliceBlue”>
            Example page where a modal popup can only be hidden by pressing the escape key
            </p>
            <asp:Button ID=”btnShowModal” runat=”server” Text=”Click to Show the Page Modal” />
            <asp:Panel ID=”pnlModalPanel” runat=”server” Style=”display: none”>
                To close this is to press the ‘esc’ key.
            </asp:Panel>
            <ajaxToolkit:ModalPopupExtender
                ID=”mdlPopupExtender” runat=”server”
                BackgroundCssClass=”modalBackground”
                TargetControlID=”btnShowModal”
                PopupControlID=”pnlModalPanel”  />
        </div>
    </form>
</body>
</html>

Hope this helps

Good Luck

May 14, 2009

Ajax Control Toolkit Installation in Visual Studio 2008

Filed under: AJAX — yasserzaid @ 3:48 pm

Hi

try the following steps to setup AJAX Toolkit in VS 2008

1- To install the Ajax Control Toolkit, first download the zip file from http://www.asp.net/ajax/.

3.5 SP1 Release is here.

2- Unzip the files into any directory. Give it a name like “AjaxControlToolkit.” 

3- Open your Visual Web Developer and right click in the Toolbox area. Select “Add Tab.” 

Name the tab with something like “Ajax Tookit.”

Right click the new tab area, and select “Choose Items…” 

This will bring up a dialog box to “Choose Toolbox Items.” Select the “Browse” button.

4- Browse to the directory where you unzipped the Ajax Toolkit files. There is a “SampleWebSite” directory within your “AjaxControlToolkit” directory. Browse to the “Bin” directory within the “SampleWebSite” directory. 

5- Find and select to open the “AjaxControlToolkit.dll” file.

6- The Choose Toolbox Items dialog will appear, this time with the Ajax Tookit controls selected. Select the “OK” button. 

7- Open or create a web form within your project. Now when you open your toolbox, you will see all of the Ajax Control Toolkit controls, ready for use within your applications. 

Hope this helps

Good Luck

May 13, 2009

AJAX Modal Popup with Ajax Slide Show

Filed under: AJAX — yasserzaid @ 10:51 am

Hi

try this example to open Modal Popup Extender with AJAX Slide Show Extender

<%@ Page Language=”C#” %>

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”cc1″ %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>

<script runat=”Server” type=”text/C#”>
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public static AjaxControlToolkit.Slide[] GetSlides()
    {
        return new AjaxControlToolkit.Slide[] {
            new AjaxControlToolkit.Slide(“SlideShow/images/Sunset.jpg”, “Sunset”, “Setting sun”),
            new AjaxControlToolkit.Slide(“SlideShow/images/Winter.jpg”, “Winter”, “Wintery…”),
            new AjaxControlToolkit.Slide(“SlideShow/images/Water lilies.jpg”, “Water lillies”, “Lillies in the water”),
            new AjaxControlToolkit.Slide(“SlideShow/images/VerticalPicture.jpg”, “Sedona”, “Portrait style picture”)};
    }
</script>

<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
    <title></title>
    <script type=”text/javascript”>
        function getid() {
            var id = $get(“Image1″).src;
            alert(id);
        }
        function Button1_onclick() {
            $find(“Panel1″).show();
        }

        function Button2_onclick() {
            $find(“Panel1″).hide();
        }

    </script>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <cc1:ToolkitScriptManager ID=”ToolkitScriptManager1″ runat=”server”>
        </cc1:ToolkitScriptManager>
        <asp:Panel ID=”Panel1″ runat=”server” Height=”311px” Width=”321px”>
        <asp:Image ID=”Image1″ runat=”server” Height=”300″ Style=”border: 1px solid black;
            width: auto” onclick=”getid();” />
        <cc1:SlideShowExtender ID=”slideshowextend1″ runat=”server” TargetControlID=”Image1″
            BehaviorID=”ss1″ SlideShowServiceMethod=”GetSlides” PlayInterval=”1000″ AutoPlay=”true”
            Loop=”true” />
            <br />
            <asp:Button ID=”Button2″ runat=”server” Text=”Close” />
            </asp:Panel>
        <cc1:ModalPopupExtender ID=”Panel1_ModalPopupExtender” runat=”server”
            DynamicServicePath=”" Enabled=”True” PopupControlID=”Panel1″ BehaviorID=”Panel1″ TargetControlID=”Panel1″ OkControlID=”Button2″>
        </cc1:ModalPopupExtender>
    </div>
    </form>
    <p>
        <input id=”Button1″ type=”button” value=”button” onclick=”return Button1_onclick()” /></p>
</body>
</html>

 Hope this helps

Good Luck

May 8, 2009

Implementing Autocomplete Textbox in GridView using AJAX Autocomplete Extender

Filed under: AJAX, ASP.Net — yasserzaid @ 6:02 pm

Hi

try this example to Add AJAX Autocomplete Extender in Edit mode with Gridview to update Data

step1 : Open SQL server 2005 and create new database has table called “Test” which has the following fields:

* ID -> int , PK , Identity

* Name -> nvarchar(50)

* Location -> nvarchar(50)

step2 : create new AJAX Website and add new web page

<body>
    <form id=”form1″ runat=”server”>
        <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
        <Services>
        <asp:ServiceReference Path=”AutoComplete.asmx” />
        </Services>
        </asp:ScriptManager>
        <asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
            <ContentTemplate>
            <asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” DataSourceID=”SqlDataSource1″>
                <Columns>
                    <asp:CommandField ShowEditButton=”True” />
                    <asp:TemplateField HeaderText=”ID” SortExpression=”ID”>
                    <ItemTemplate>
                    <asp:Label ID=”lblID” runat=”server” Text=’<%#Eval(“ID”) %>’></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                    <asp:Label ID=”lblID” runat=”server” Text=’<%#Bind(“ID”) %>’></asp:Label>
                    </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText=”Name” SortExpression=”Name”>
                    <ItemTemplate>
                    <asp:Label ID = “lblName” runat=”server” Text=’<%#Eval(“Name”) %>’></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                    <asp:TextBox ID=”txtName” runat=”server” Text=’<%#Bind(“Name”) %>’ ></asp:TextBox>
                    <ajaxToolkit:AutoCompleteExtender
                                 runat=”server”
                                 ID=”autoComplete1″
                                 TargetControlID=”txtName”
                                 ServicePath=”AutoComplete.asmx”
                                 ServiceMethod=”GetCompletionList”
                                 MinimumPrefixLength=”1″
                                 CompletionInterval=”10″
                                 EnableCaching=”true”
                                 CompletionSetCount=”12″ />
                    </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText=”Location” SortExpression=”Location”>
                    <ItemTemplate>
                    <asp:Label ID=”lblLocation” runat=”server” Text=’<%#Eval(“Location”) %>’></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                    <asp:Label ID=”lblLocation” runat=”server” Text=’<%#Bind(“Location”) %>’></asp:Label>
                    </EditItemTemplate>
                    </asp:TemplateField>
                   
                    </Columns>
            </asp:GridView>
            </ContentTemplate>
        </asp:UpdatePanel>
        <div>           
            <asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:DatabaseConnectionString %>”
                SelectCommand=”SELECT [ID], [Name], [Location] FROM [Test]” UpdateCommand=”Update Test set [Name] = @Name where ID = @ID”>
                <UpdateParameters>
                    <asp:Parameter Name=”Name” />
                    <asp:Parameter Name=”ID” />
                </UpdateParameters>
            </asp:SqlDataSource>
    </div>
    </form>  
</body>

step3 : Add new WebService called “AutoComplete.asmx”

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.Sql;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService] //——

public class AutoComplete : System.Web.Services.WebService {

    public AutoComplete () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    { if (count == 0)
    {
        count = 10;
    }
        DataTable dt = GetRecords(prefixText);
        List<string> items = new List<string>(count);
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string strName = dt.Rows[i][0].ToString();
            items.Add(strName);
        }
        return items.ToArray();
    }   
   
    public DataTable GetRecords(string strName)
    {
        string strConn = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Parameters.AddWithValue(“@Name”, strName); cmd.CommandText = “Select Name from Test where Name like ‘%’+@Name+’%'”;
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd; con.Open();
        dAdapter.Fill(objDs); con.Close();
        return objDs.Tables[0]; }
   
}

 

so when user want to update and write Name will filter with Name the user write in TextBox from database 

 Hope this helps

Good Luck

May 1, 2009

AJAX Update Progress with CSS

Filed under: AJAX, CSS — yasserzaid @ 11:12 pm

Hi

try this example to use AJAX Update Progress with CSS

<asp:UpdateProgress ID=”UpdateProgress1″ runat=”server”>   
<ProgressTemplate>
        <div id=”Progress”>Please wait ……</div>
       <div id=”bgDiv”></div>
</ProgressTemplate>
</asp:UpdateProgress>

and CSS

<style>       
#bgDiv
{         
position:absolute;         
top:0px;
bottom:0px;         
left:0px;         
right:0px;
overflow:hidden;
padding:0;
margin:0;
background-color:black;
filter:alpha(opacity=50);
opacity:0.5;
z-index:500;
}

#Progress
{
position: absolute;
background-color:Red;
width: 300px;
z-index: 600;
}
</style>

Good Luck

April 12, 2009

AJAX ModalPopup with FileUpload

Filed under: AJAX — yasserzaid @ 5:11 pm

Hi

try this example :-

<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>

<script runat=”server”>

    protected void ButtonOk_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            if (FileUpload1.PostedFile.ContentLength < 4096)
            {
                FileUpload1.SaveAs(Server.MapPath(“”) + FileUpload1.FileName);
            }
        }
    }
</script>

<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
    <title></title>
    <style type=”text/css”>
        .modalBackground
        {
            position: absolute;
            z-index: 100;
            top: 0px;
            left: 0px;
            background-color: #000;
            filter: alpha(opacity=60);
            -moz-opacity: 0.6;
            opacity: 0.6;
        }
    </style>

</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:ScriptManager ID=”ScriptManager1″ runat=”server” />
        <asp:Panel ID=”Panel1″ runat=”server” Height=”97px” Width=”259px”
            BackColor=”Red”>
            <asp:FileUpload ID=”FileUpload1″ runat=”server” />
            <br />
            <asp:Button ID=”ButtonOk” runat=”server” Text=”OK” />
            <asp:Button ID=”ButtonCancel” runat=”server” Text=”Cancel” />
        </asp:Panel>
        <asp:Button ID=”Button1″ runat=”server” Text=”Button” />
        <ajaxToolkit:ModalPopupExtender ID=”Button1_ModalPopupExtender” runat=”server” DynamicServicePath=”"
            Enabled=”True” TargetControlID=”Button1″ PopupControlID=”Panel1″ BackgroundCssClass=”modalBackground”
            CancelControlID=”ButtonCancel” BehaviorID=”Button1_ModalPopupExtender”>
        </ajaxToolkit:ModalPopupExtender>
    </div>
    </form>
</body>
</html>

Good Luck

March 27, 2009

AJAX Modal Popup Extender to Delete With Confirmation From Gridview

Filed under: AJAX — Tags: — yasserzaid @ 6:17 pm

Hi

try this example to use AJAX Modal Popup Extender to Delete With Confirmation From Gridview

In this Example i will use Products Table from Northwind Database

.ASPX

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default3.aspx.cs” Inherits=”Default3″ %>

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”cc1″ %>

<!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>ModalPopup for Delete</title>
    <style type=”text/css”>
    .modalBackground {
            background-color:Gray;
            filter:alpha(opacity=70);
            opacity:0.7;
        }
        .confirm{
           background-color:White;
           padding:10px;
           width:370px;
        }
    </style>
   
    <script type=”text/javascript”>
        //  keeps track of the delete button for the row
        //  that is going to be removed
        var _source;
        // keep track of the popup div
        var _popup;
       
        function showConfirm(source){
            this._source = source;
            this._popup = $find(‘mdlPopup’);
           
            //  find the confirm ModalPopup and show it   
            this._popup.show();
        }
       
        function okClick(){
            //  find the confirm ModalPopup and hide it   
            this._popup.hide();
            //  use the cached button as the postback source
            __doPostBack(this._source.name, ”);
        }
       
        function cancelClick(){
            //  find the confirm ModalPopup and hide it
            this._popup.hide();
            //  clear the event source
            this._source = null;
            this._popup = null;
        }
    </script>
   
</head>
<body>
    <form id=”form1″ runat=”server”>
        <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
        </asp:ScriptManager>
       
        <asp:UpdateProgress ID=”UpdateProgress1″ runat=”server” AssociatedUpdatePanelID=”UpdatePanel1″>
            <ProgressTemplate>
                <div id=”progressBackgroundFilter”>
                </div>
                <div id=”processMessage”>
                    Please Wait …..</div>
            </ProgressTemplate>
        </asp:UpdateProgress>
        <cc1:modalpopupextender id=”md1″ runat=”server” backgroundcssclass=”modalBackground”
            behaviorid=”mdlPopup” cancelcontrolid=”btnNo” okcontrolid=”btnOk” oncancelscript=”cancelClick();”
            onokscript=”okClick();” popupcontrolid=”div” targetcontrolid=”div”> </cc1:modalpopupextender>
        <div id=”div” runat=”server” align=”center” class=”confirm” style=”display: none”>
            Are you sure you want to delete ?
            <asp:Button ID=”btnOk” runat=”server” Text=”Yes” Width=”50px” />
            <asp:Button ID=”btnNo” runat=”server” Text=”No” Width=”50px” />
        </div>
        <asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
            <ContentTemplate>
                &nbsp;<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” CellPadding=”4″
                    DataKeyNames=”ProductID” DataSourceID=”SqlDataSource1″ ForeColor=”#333333″ AllowPaging=”True”>
                    <FooterStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
                    <Columns>
                        <asp:BoundField DataField=”ProductName” HeaderText=”ProductName” SortExpression=”ProductName” />
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:Button ID=”Button1″ runat=”server” CausesValidation=”False” CommandArgument=’<%# Eval(“ProductID”) %>’
                                    OnClick=”Button1_Click” OnClientClick=”showConfirm(this); return false;” Text=”Delete” />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <RowStyle BackColor=”#EFF3FB” />
                    <EditRowStyle BackColor=”#2461BF” />
                    <SelectedRowStyle BackColor=”#D1DDF1″ Font-Bold=”True” ForeColor=”#333333″ />
                    <PagerStyle BackColor=”#2461BF” ForeColor=”White” HorizontalAlign=”Center” />
                    <HeaderStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
                    <AlternatingRowStyle BackColor=”White” />
                </asp:GridView>
                <asp: SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings: NorthwindConnectionString %>”
                    SelectCommand=”SELECT [ProductID], [ProductName] FROM [Products]“></asp: SqlDataSource>
            </ContentTemplate>

Hope this helps

Good Luck
        </asp: UpdatePanel>
    </form>
</body>
</html>

and In Code behind :-

protected void Button1_Click(object sender, EventArgs e)
    {
        //  get the gridviewrow from the sender so we can get the datakey we need
        Button btnDelete = sender as Button;
        //GridViewRow row = (GridViewRow)btnDelete.NamingContainer;
        int ProductID = int.Parse(btnDelete.CommandArgument);
        ///– you delete Method here
    }

and in web.config file :-

<connectionStrings>
  < add name=”NorthwindConnectionString” connectionString=”Data Source=.;Initial Catalog=Northwind;Integrated Security=True” providerName=”System.Data.SqlClient”/>
 </connectionStrings>

Good Luck

Older Posts »

Blog at WordPress.com.