Sunday, October 23, 2011

ListView and DataPager Controls: Inserting Data with DropDownlist


Introduction


The ListView control is similar to the GridView control in many ways: both display a set of records, both support built-in sorting, paging, editing, and deleting functionality with minimal effort. The ListView differs from the GridView in two key ways:
  • Rather than using fields, the ListView is rendered via templates, which offers the page developer much finer control over the emitted markup, and
  • The ListView supports built-in inserting support
The first installment in this series explored the ListView's template-based rendering. This installment looks at how to use the ListView's inserting functionality.In a nutshell, inserting data from the ListView requires two steps: defining the inserting interface via the InsertItemTemplate and specifying where the inserting interface should go via the InsertItemPosition property. Much like with editing data from within the ListView, the InsertItemTemplate can contain two-way databinding statements when using a data source control to get the inputs entered by the user from the ListView's inserting interface into the parameters of the data source control. And like with the editing and deleting workflows, you can programmatically examine and modify the user's submitted data before inserting the data, cancelling the operation altogether if needed.
This article walks through the steps for creating a ListView that allows users to insert records. It also shows how to optionally cancel the inserting workflow based on programmatic logic. Read on to learn more!


An Overview of the ListView's Inserting Workflow


A ListView control that supports inserting includes some sort of inserting interface. This interface includes input Web controls to collect the data to add a new record - TextBoxes, CheckBoxes, DropDownLists, and so forth - along with Insert and Cancel buttons. Clicking the Insert button adds a new record using the user-supplied values; the Cancel button, when clicked, resets the inserting interface to its initial state by clearing out the TextBoxes, returning the DropDownLists to the first item, and so on.The screen shot below shows a ListView control that has an inserting interface defined and has it displayed as the first item. In other words, it appears before any other content defined in the ItemTemplate. The inserting interface may be displayed as the first or last item; it's location is configured via the InsertItemPosition property. The Insert button in the screen shot below is implemented as an ImageButton and displays a green plus icon.

The inserting interface is displayed before any other items in the ListView.
Clicking the Insert button causes a postback and starts the ListView down the inserting workflow path:
  1. The ListView raises its ItemInserting event.
  2. The ListView assigns the values supplied in the inserting interface to the insert parameters for its associated data source control.
  3. The ListView calls its associated data source control's Insert method, which actually performs the insert.
  4. The ListView raises its ItemInserted event handler.
  5. The ListView rebinds to its data source.
After the inserting workflow completes, the just-added item is included in the ListView and the inserting interface is returned to its initial state (the TextBoxes are cleared out, the DropDownLists reset to the first list item, etc.) because the data is rebound to the ListView (step 5) after the insert is performed (step 3).From the end user's perspective, the inserting workflow unfolds like this: the enters the values for the new record into the TextBoxes, DropDownLists, and other input Web controls in the inserting interface. Next, she clicks the Insert button; there's a short pause and the inserting interface is returned to its initial state and the just-added record is displayed in the ListView.

Implementing the Inserting Interface (InsertItemTemplate) and Setting the 


Adding inserting support to the ListView requires that the ListView's underlying data source control support inserting. That means that if you are using a SqlDataSource or AccessDataSource control as the ListView's data source that the SqlDataSource (or AccessDataSource) must have an InsertCommand specified. If you are using an ObjectDataSource then you will need to have specified what object method to invoke to perform the insert. For more background on configuring the data source controls to support inserting, refer to Accessing and Updating Data in ASP.NET: Inserting Data.Recall that implementing inserting involves two key steps: defining the inserting interface via the InsertItemTemplate and specifying where the inserting interface should be placed via the InsertItemPosition property. The InsertItemTemplate must contain the input Web controls to collect the user's input. The demo available for download at the end of this article shows how to insert new records into the Northwind database's Products table, allowing the user to supply the values for the new product's name, supplier, category, and price. These four values are stored in the Products table's ProductNameSupplierIDCategoryID, and UnitPrice fields, respectively.
The markup for the inserting interface (shown below) includes two TextBoxes - one for the ProductName field and one for UnitPrice - and two DropDownLists - one forSupplierID and one for CategoryID. There's also two ImageButton controls that are the Insert and Cancel buttons. The Insert and Cancel buttons can be implemented as Button, LinkButton, or ImageButton controls, but they must have their CommandName properties set to "Insert" and "Cancel", respectively.
Finally, the markup below also includes the assignment of the InsertItemPosition to the value "FirstItem". This property can be set to "FirstItem", "LastItem", or "None". Setting it to "FirstItem" displays the inserting interface before any of the ListView's rendered items.

<asp:ListView InsertItemPosition="FirstItem" ID="lvProducts" runat="server" DataSourceID="dsNorthwind">
   ...
  
   <InsertItemTemplate>
      <p>
         <b>Product Name:</b>
         <asp:TextBox ID="txtProductName" runat="server" Text='<%# Bind("ProductName") %>'></asp:TextBox>
         <asp:RequiredFieldValidator ID="rfvProductName" ControlToValidate="txtProductName" Display="Dynamic"
                            runat="server" ErrorMessage="[Required]"></asp:RequiredFieldValidator>
         <br />
        
         <b>Supplier:</b>
         <asp:DropDownList ID="ddlSuppliers" runat="server" DataSourceID="dsSuppliers" AppendDataBoundItems="true"
               DataTextField="CompanyName" DataValueField="SupplierID">
            <asp:ListItem Value="">None / Unknown</asp:ListItem>
         </asp:DropDownList>
         <br />
        
         <b>Category:</b>
         <asp:DropDownList ID="ddlCategories" runat="server" DataSourceID="dsCategories" AppendDataBoundItems="true"
               DataTextField="CategoryName" DataValueField="CategoryID">
            <asp:ListItem Value="">None / Unknown</asp:ListItem>
         </asp:DropDownList>
         <br />

         <b>Price:</b>
         $<asp:TextBox ID="txtUnitPrice" runat="server" Text='<%# Bind("UnitPrice", "{0:N2}") %>'></asp:TextBox>
         <asp:CompareValidator ID="cvUnitPrice" ControlToValidate="txtUnitPrice" runat="server"
               ErrorMessage="[Invalid]" Operator="GreaterThanEqual" ValueToCompare="0" Type="Currency"></asp:CompareValidator>
         <br />
      </p>
     
      <p>
         <asp:ImageButton ID="imgbInsertProduct" runat="server" ToolTip="Insert Product" AlternateText="Insert Product"
                     CommandName="Insert" ImageUrl="~/Images/add.png" />
         <asp:ImageButton ID="imgbCancelInsert" runat="server" ToolTip="Cancel" AlternateText="Cancel"
                  CausesValidation="false" CommandName="Cancel" ImageUrl="~/Images/cancel.png" />
      </p>
   </InsertItemTemplate>
</asp:ListView>

As the markup above illustrates, the InsertItemTemplate can also include validation Web controls. The txtProductName TextBox has a RequiredFieldValidator associated with it, as the ProductName field is required, and the txtUnitPrice TextBox has a CompareValidator to ensure that a non-negative, currency-formatted value is supplied.

Validation With a ListView That Supports Inserting and Editing
The ListView used in this demo supports inserting, but does not support editing. However, it is possible to create a ListView that provides both inserting and editing functionality. If you create such a ListView and add validation controls to both the inserting and editing interfaces you may find that you cannot update a record until you "satisfy" the validators in the inserting interface. This is because by default ASP.NET checks all validation controls on the page when submitting. Long story short, even though the user is not inserting a record the Update button from the editing interface triggers the inserting-related validation controls to fire.The good news is that it's easy to partition the validation controls into separate validation groups - one for inserting and one for editing - which alleviates this issue. For more information on ASP.NET's validation controls and separating them into distinct groups, refer to Dissecting the Validation Controls in ASP.NET.


Two-Way Databinding in the Inserting Interface


As discussed in the Editing Data installment we explored how to use ASP.NET's two-way databinding syntax to get the values entered by the user into the editing interface into the data source control's update parameters. In short, you use the Bind statement to both assign a value into a Web control property when the editing interface is displayed and to take the value of that property and send it back out to the update parameters when the Update button is clicked. For example, with a TextBox you'd use the Bind statement on the Text property like so:
<asp:TextBox ID="ID" runat="server" Text='<%# Bind("columnName") %>' />

The inserting interface shown above includes Bind statements on the txtProductName and txtUnitPrice TextBox controls. When the user clicks the Insert button the ListView takes the values entered into these TextBoxes and puts them in the corresponding insert parameters in its data source control. You may have noticed that there are no Bind statements on the DropDownLists. Usually you'd have a Bind statement on the DropDownList's SelectedValue property. However, if you are using ASP.NET version 3.5 and add such a Bind statement you'll get the following error when visiting the page in a browser: System.InvalidOperationException: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
This behavior is a bug in the ListView control in ASP.NET version 3.5. According to Microsoft it will be fixed in ASP.NET version 4.0. In the meantime to work around it you need to do the following:
  • Remove any Bind statements from the DropDownList controls in the InsertItemTemplate
  • Create an event handler for the ListView's ItemInserting event, which fires after the user has clicked the Insert button but before the insert command is sent to the data source control
  • Programmatically reference the DropDownList control(s) in the InsertItemTemplate using the syntax: e.Item.FindControl("DDLcontrolID")
  • Set the appropriate value(s) in the e.Values collection to the SelectedValue property of the DropDownList control(s)
The code for the ItemInserting event handler follows. Note that if you are using C# you would reference the Values collection items using square brackets instead of parentheses, like: e.Values["CategoryID"] = ....
Protected Sub lvProducts_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewInsertEventArgs) Handles lvProducts.ItemInserting
   'Set the values from the DropDownLists in the InsertItemTemplate
   Dim ddlSuppliers = CType(e.Item.FindControl("ddlSuppliers"), DropDownList)
   Dim ddlCategories = CType(e.Item.FindControl("ddlCategories"), DropDownList)

   e.Values("SupplierID") = ddlSuppliers.SelectedValue
   e.Values("CategoryID") = ddlCategories.SelectedValue
End Sub

With this code in place our ListView is complete! The user can visit the page, enter values into the TextBoxes and DropDownLists in the inserting interface, and click the Insert button to add a new record to the Products table.
The screen shots below show the end user's experience as she adds a new product to the database. The first screen shot shows the inserting interface after the user has entered in the new product's information. The second screen shot shows the ListView after the user has clicked the Insert button. Note that the inserting interface is returned to its initial state and the ListView displays the just-added record.

A new product, Scott's Ale, is being added to the Products table.


After clicking the Insert button, the product is added to the database and displayed in the ListView.

Short-Circuiting the Inserting Workflow


In some scenarios you may want to cancel the inserting workflow based on the user's input or some other type of programmatic logic. Perhaps the range of values that a user can enter for the new product's price depend on the supplier or category, or maybe there are certain business rules that disallow certain supplier/category pairings.Whatever the rationale may be, you have an opportunity to examine the values to be inserted before the insert is committed via the ItemInserting event handler. The demo available at the end of this article includes such an event handler that checks to see if the ProductName value entered by the user contains more than three words. If such a lengthy product name is found then the update is canceled and the user is shown a message explaining the issue.
The code for the ItemInserting event handler is straightforward. It pulls the value entered into the ProductName field via the e.Values collection. It then splits on spaces (" "). If there are more than two spaces in the product name then, presumably, there are more than three words, so the update is canceled by setting e.Cancel to True and a message is displayed via the DisplayAlert method, which is defined in a custom base Page class. If the check passes then the values from the DropDownLists are assigned to the appropriate parameters in the Values collection and a message is displayed informing the user that their product was added.

Protected Sub lvProducts_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewInsertEventArgs) Handles lvProducts.ItemInserting
   'Make sure product name does not contain more than three words
   'Split on " "
   Dim words() As String = e.Values("ProductName").ToString().Trim().Split(New Char() {" "})

   If words.Length > 2 Then
      'Invalid product name!
      e.Cancel = True

      MyBase.DisplayAlert("You cannot have more than three words in the product name. Please shorten your product name and try again.")
   
Else
      'Data is kosher, so set the values from the DropDownLists in the InsertItemTemplate
      Dim ddlSuppliers = CType(e.Item.FindControl("ddlSuppliers"), DropDownList)
      Dim ddlCategories = CType(e.Item.FindControl("ddlCategories"), DropDownList)

      e.Values("SupplierID") = ddlSuppliers.SelectedValue
      e.Values("CategoryID") = ddlCategories.SelectedValue

      MyBase.DisplayAlert(String.Format("The product {0} has been added.", e.Values("ProductName").ToString()))
   End If
End Sub 

The following screen shot shows the client-side messagebox that is displayed when the user attempts to add a new product with a name that's more than three words (such as "Aniseed Syrup Is Good!")

Product names with more than three words are not permitted.

Conclusion


The ListView control provides inserting, updating, and deleting functionality. As we saw in this installment, adding inserting capabilities to the ListView is relatively straightforward: create an inserting interface and set the ListView's InsertItemPosition property to either "FirstItem" or "LastItem", depending on where you want the inserting interface to appear. Keep in mind that in the inserting interface you cannot use two-way databinding to retrieve data from a DropDownList control; instead, you have to programmatically reference the DropDownLists and assign their SelectedValue properties to the appropriate values in the Values collection. This assignment can be performed from the ListView's ItemInserting event handler. And that's it! The data source control handles the actual insert logic.

3:04 AM by Dilip kakadiya · 0

Saturday, October 22, 2011

User validation authentication using session in ASP.NET


For Forms Authentication, read this Forms Authentication with C# and managing folder lavel access with multiple web.config files in ASP.NET


In this example i m showing how to validate a user across different pages whether user is logged in or not using session variables in Global.asax through Session_Start event and Application_OnPostRequestHandlerExecute event which checks for the login validation which occurs when ant asp.net event handler finish execution
Here is my login page , i've used hard coded values to login

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Login.aspx.cs" Inherits="_Default" %>


<!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">
<div style="text-align:left" >
<table width="40%" style="text-align: center">
<tr><td style="width: 20%">
<asp:Label ID="lblUserName"
runat="server" Text="Enter UserName:">
</asp:Label></td>
<td style="width: 20%">
<asp:TextBox ID="txtUserName"
runat="server">
</asp:TextBox></td>
</tr>
<tr>
<td style="width: 20%">
<asp:Label ID="lblPassword" runat="server"
Text="Enter Password:">
</asp:Label></td>
<td style="width: 20%" >
<asp:TextBox ID="txtPassword" runat="server"
TextMode="Password">
</asp:TextBox></td>
</tr><tr><td colspan="2" align="right">
<asp:Button ID="btnLogin" runat="server"
Text="Sign in" OnClick="btnLogin_Click" />
</td></tr>
</table>
<asp:Label ID="Label1" runat="server"
Text="Label">
</asp:Label><br />
</div>


</form>
</body>
</html>

After checking the username and password i m creating a new Session variable and setting the flag kindaa value in it , which is "Yes" in this example, this session value will be checked when ever user go to other pages and if it's null than user in not logged in
protected void btnLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "amit" && txtPassword.Text == "amit")
{
Session["Authenticate"] = "Yes";
Response.Redirect("Default2.aspx");
}
else
Label1.Text = " login failed";
}

In Global.asax, in Session_Start event i m assigning null value to the session variable created at the time of Login and than calling the method to check the login, same is in Application_OnPostRequestHandlerExecute event as well 
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["Authenticate"] = "";
CheckLogin();

}
void Application_OnPostRequestHandlerExecute()
{
CheckLogin();
}

void CheckLogin()
{
string Url = Request.RawUrl;
int count = Url.Length - 10 ;
string TestUrl = Url.Substring(count);
string SessionData = Session["Authenticate"].ToString();
if (SessionData == "" && TestUrl != "Login.aspx")
{
Response.Redirect("~/Login.aspx");
}
}


Download the sample code attached 


4:14 AM by Dilip kakadiya · 0

Dialog window with Javascript


OVERVIEW

A dialog is a floating window that contains a title bar and a content area. The dialog window can be moved, resized and closed with the 'x' icon by default.
If the content length exceeds the maximum height, a scrollbar will automatically appear.
A bottom button bar and semi-transparent modal overlay layer are common options that can be added.
A call to $(foo).dialog() will initialize a dialog instance and will auto-open the dialog by default. If you want to reuse a dialog, the easiest way is to disable the "auto-open" option with:$(foo).dialog({ autoOpen: false }) and open it with $(foo).dialog('open'). To close it, use $(foo).dialog('close'). A more in-depth explanation with a full demo is available on the Nemikor blog.

Dependencies

  • UI Core
  • UI Position
  • UI Widget
  • UI Mouse (Optional; only needed if using UI Draggable or UI Resizable)
  • UI Draggable (Optional)
  • UI Resizable (Optional)

Example

$("#dialog").dialog();
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

<script>
$(document).ready(function() {
$("#dialog").dialog();
});
</script>
</head>
<body style="font-size:62.5%;">

<div id="dialog" title="Dialog Title">I'm in a dialog</div>

</body>
</html>

Options

  • disabled

    Boolean
    Default:
    false
    Disables (true) or enables (false) the dialog. Can be set when initialising (first creating) the dialog.

    Code examples

    Initialize a dialog with the disabled option specified.
    $( ".selector" ).dialog({ disabled: true });
    Get or set the disabled option, after init.
    //getter
    var disabled = $( ".selector" ).dialog( "option", "disabled" );
    //setter
    $( ".selector" ).dialog( "option", "disabled", true );



  • autoOpen

    Boolean
    Default:
    true
    When autoOpen is true the dialog will open automatically when dialog is called. If false it will stay hidden until .dialog("open") is called on it.

    Code examples

    Initialize a dialog with the autoOpen option specified.
    $( ".selector" ).dialog({ autoOpen: false });
    Get or set the autoOpen option, after init.
    //getter
    var autoOpen = $( ".selector" ).dialog( "option", "autoOpen" );
    //setter
    $( ".selector" ).dialog( "option", "autoOpen", false );



  • buttons

    Object
    Default:
    { }
    Specifies which buttons should be displayed on the dialog. The property key is the text of the button. The value is the callback function for when the button is clicked. The context of the callback is the dialog element; if you need access to the button, it is available as the target of the event object.

    Code examples

    Initialize a dialog with the buttons option specified.
    $( ".selector" ).dialog({ buttons: { "Ok": function() { $(this).dialog("close"); } } });
    Get or set the buttons option, after init.
    //getter
    var buttons = $( ".selector" ).dialog( "option", "buttons" );
    //setter
    $( ".selector" ).dialog( "option", "buttons", { "Ok": function() { $(this).dialog("close"); } } );



  • buttons

    Array
    Default:
    [ ]
    Specifies which buttons should be displayed on the dialog. Each element of the array must be an Object defining the properties to set on the button.

    Code examples

    Initialize a dialog with the buttons option specified.
    $( ".selector" ).dialog({ buttons: [
    {
    text: "Ok",
    click: function() { $(this).dialog("close"); }
    }
    ] });
    Get or set the buttons option, after init.
    //getter
    var buttons = $( ".selector" ).dialog( "option", "buttons" );
    //setter
    $( ".selector" ).dialog( "option", "buttons", [
    {
    text: "Ok",
    click: function() { $(this).dialog("close"); }
    }
    ] );



  • closeOnEscape

    Boolean
    Default:
    true
    Specifies whether the dialog should close when it has focus and the user presses the esacpe (ESC) key.

    Code examples

    Initialize a dialog with the closeOnEscape option specified.
    $( ".selector" ).dialog({ closeOnEscape: false });
    Get or set the closeOnEscape option, after init.
    //getter
    var closeOnEscape = $( ".selector" ).dialog( "option", "closeOnEscape" );
    //setter
    $( ".selector" ).dialog( "option", "closeOnEscape", false );



  • closeText

    String
    Default:
    'close'
    Specifies the text for the close button. Note that the close text is visibly hidden when using a standard theme.

    Code examples

    Initialize a dialog with the closeText option specified.
    $( ".selector" ).dialog({ closeText: 'hide' });
    Get or set the closeText option, after init.
    //getter
    var closeText = $( ".selector" ).dialog( "option", "closeText" );
    //setter
    $( ".selector" ).dialog( "option", "closeText", 'hide' );



  • dialogClass

    String
    Default:
    ''
    The specified class name(s) will be added to the dialog, for additional theming.

    Code examples

    Initialize a dialog with the dialogClass option specified.
    $( ".selector" ).dialog({ dialogClass: 'alert' });
    Get or set the dialogClass option, after init.
    //getter
    var dialogClass = $( ".selector" ).dialog( "option", "dialogClass" );
    //setter
    $( ".selector" ).dialog( "option", "dialogClass", 'alert' );



  • draggable

    Boolean
    Default:
    true
    If set to true, the dialog will be draggable will be draggable by the titlebar.

    Code examples

    Initialize a dialog with the draggable option specified.
    $( ".selector" ).dialog({ draggable: false });
    Get or set the draggable option, after init.
    //getter
    var draggable = $( ".selector" ).dialog( "option", "draggable" );
    //setter
    $( ".selector" ).dialog( "option", "draggable", false );



  • height

    Number
    Default:
    'auto'
    The height of the dialog, in pixels. Specifying 'auto' is also supported to make the dialog adjust based on its content.

    Code examples

    Initialize a dialog with the height option specified.
    $( ".selector" ).dialog({ height: 530 });
    Get or set the height option, after init.
    //getter
    var height = $( ".selector" ).dialog( "option", "height" );
    //setter
    $( ".selector" ).dialog( "option", "height", 530 );



  • hide

    String, Object
    Default:
    null
    The effect to be used when the dialog is closed.

    Code examples

    Initialize a dialog with the hide option specified.
    $( ".selector" ).dialog({ hide: 'slide' });
    Get or set the hide option, after init.
    //getter
    var hide = $( ".selector" ).dialog( "option", "hide" );
    //setter
    $( ".selector" ).dialog( "option", "hide", 'slide' );



  • maxHeight

    Number
    Default:
    false
    The maximum height to which the dialog can be resized, in pixels.

    Code examples

    Initialize a dialog with the maxHeight option specified.
    $( ".selector" ).dialog({ maxHeight: 400 });
    Get or set the maxHeight option, after init.
    //getter
    var maxHeight = $( ".selector" ).dialog( "option", "maxHeight" );
    //setter
    $( ".selector" ).dialog( "option", "maxHeight", 400 );



  • maxWidth

    Number
    Default:
    false
    The maximum width to which the dialog can be resized, in pixels.

    Code examples

    Initialize a dialog with the maxWidth option specified.
    $( ".selector" ).dialog({ maxWidth: 600 });
    Get or set the maxWidth option, after init.
    //getter
    var maxWidth = $( ".selector" ).dialog( "option", "maxWidth" );
    //setter
    $( ".selector" ).dialog( "option", "maxWidth", 600 );



  • minHeight

    Number
    Default:
    150
    The minimum height to which the dialog can be resized, in pixels.

    Code examples

    Initialize a dialog with the minHeight option specified.
    $( ".selector" ).dialog({ minHeight: 300 });
    Get or set the minHeight option, after init.
    //getter
    var minHeight = $( ".selector" ).dialog( "option", "minHeight" );
    //setter
    $( ".selector" ).dialog( "option", "minHeight", 300 );



  • minWidth

    Number
    Default:
    150
    The minimum width to which the dialog can be resized, in pixels.

    Code examples

    Initialize a dialog with the minWidth option specified.
    $( ".selector" ).dialog({ minWidth: 400 });
    Get or set the minWidth option, after init.
    //getter
    var minWidth = $( ".selector" ).dialog( "option", "minWidth" );
    //setter
    $( ".selector" ).dialog( "option", "minWidth", 400 );



  • modal

    Boolean
    Default:
    false
    If set to true, the dialog will have modal behavior; other items on the page will be disabled (i.e. cannot be interacted with). Modal dialogs create an overlay below the dialog but above other page elements.

    Code examples

    Initialize a dialog with the modal option specified.
    $( ".selector" ).dialog({ modal: true });
    Get or set the modal option, after init.
    //getter
    var modal = $( ".selector" ).dialog( "option", "modal" );
    //setter
    $( ".selector" ).dialog( "option", "modal", true );



  • position

    String, Array
    Default:
    'center'
    Specifies where the dialog should be displayed. Possible values:
    1) a single string representing position within viewport: 'center', 'left', 'right', 'top', 'bottom'.
    2) an array containing an x,y coordinate pair in pixel offset from left, top corner of viewport (e.g. [350,100])
    3) an array containing x,y position string values (e.g. ['right','top'] for top right corner).

    Code examples

    Initialize a dialog with the position option specified.
    $( ".selector" ).dialog({ position: 'top' });
    Get or set the position option, after init.
    //getter
    var position = $( ".selector" ).dialog( "option", "position" );
    //setter
    $( ".selector" ).dialog( "option", "position", 'top' );



  • resizable

    Boolean
    Default:
    true
    If set to true, the dialog will be resizeable.

    Code examples

    Initialize a dialog with the resizable option specified.
    $( ".selector" ).dialog({ resizable: false });
    Get or set the resizable option, after init.
    //getter
    var resizable = $( ".selector" ).dialog( "option", "resizable" );
    //setter
    $( ".selector" ).dialog( "option", "resizable", false );



  • show

    String, Object
    Default:
    null
    The effect to be used when the dialog is opened.

    Code examples

    Initialize a dialog with the show option specified.
    $( ".selector" ).dialog({ show: 'slide' });
    Get or set the show option, after init.
    //getter
    var show = $( ".selector" ).dialog( "option", "show" );
    //setter
    $( ".selector" ).dialog( "option", "show", 'slide' );



  • stack

    Boolean
    Default:
    true
    Specifies whether the dialog will stack on top of other dialogs. This will cause the dialog to move to the front of other dialogs when it gains focus.

    Code examples

    Initialize a dialog with the stack option specified.
    $( ".selector" ).dialog({ stack: false });
    Get or set the stack option, after init.
    //getter
    var stack = $( ".selector" ).dialog( "option", "stack" );
    //setter
    $( ".selector" ).dialog( "option", "stack", false );



  • title

    String
    Default:
    ''
    Specifies the title of the dialog. Any valid HTML may be set as the title. The title can also be specified by the title attribute on the dialog source element.

    Code examples

    Initialize a dialog with the title option specified.
    $( ".selector" ).dialog({ title: 'Dialog Title' });
    Get or set the title option, after init.
    //getter
    var title = $( ".selector" ).dialog( "option", "title" );
    //setter
    $( ".selector" ).dialog( "option", "title", 'Dialog Title' );



  • width

    Number
    Default:
    300
    The width of the dialog, in pixels.

    Code examples

    Initialize a dialog with the width option specified.
    $( ".selector" ).dialog({ width: 460 });
    Get or set the width option, after init.
    //getter
    var width = $( ".selector" ).dialog( "option", "width" );
    //setter
    $( ".selector" ).dialog( "option", "width", 460 );



  • zIndex

    Integer
    Default:
    1000
    The starting z-index for the dialog.

    Code examples

    Initialize a dialog with the zIndex option specified.
    $( ".selector" ).dialog({ zIndex: 3999 });
    Get or set the zIndex option, after init.
    //getter
    var zIndex = $( ".selector" ).dialog( "option", "zIndex" );
    //setter
    $( ".selector" ).dialog( "option", "zIndex", 3999 );



Events

  • create

    Type:
    dialogcreate
    This event is triggered when dialog is created.

    Code examples

    Supply a callback function to handle the create event as an init option.
    $( ".selector" ).dialog({
    create: function(event, ui) { ... }
    });
    Bind to the create event by type: dialogcreate.
    $( ".selector" ).bind( "dialogcreate", function(event, ui) {
    ...
    });



  • beforeClose

    Type:
    dialogbeforeclose
    This event is triggered when a dialog attempts to close. If the beforeClose event handler (callback function) returns false, the close will be prevented.

    Code examples

    Supply a callback function to handle the beforeClose event as an init option.
    $( ".selector" ).dialog({
    beforeClose: function(event, ui) { ... }
    });
    Bind to the beforeClose event by type: dialogbeforeclose.
    $( ".selector" ).bind( "dialogbeforeclose", function(event, ui) {
    ...
    });



  • open

    Type:
    dialogopen
    This event is triggered when dialog is opened.

    Code examples

    Supply a callback function to handle the open event as an init option.
    $( ".selector" ).dialog({
    open: function(event, ui) { ... }
    });
    Bind to the open event by type: dialogopen.
    $( ".selector" ).bind( "dialogopen", function(event, ui) {
    ...
    });



  • focus

    Type:
    dialogfocus
    This event is triggered when the dialog gains focus.

    Code examples

    Supply a callback function to handle the focus event as an init option.
    $( ".selector" ).dialog({
    focus: function(event, ui) { ... }
    });
    Bind to the focus event by type: dialogfocus.
    $( ".selector" ).bind( "dialogfocus", function(event, ui) {
    ...
    });



  • dragStart

    Type:
    dialogdragstart
    This event is triggered at the beginning of the dialog being dragged.

    Code examples

    Supply a callback function to handle the dragStart event as an init option.
    $( ".selector" ).dialog({
    dragStart: function(event, ui) { ... }
    });
    Bind to the dragStart event by type: dialogdragstart.
    $( ".selector" ).bind( "dialogdragstart", function(event, ui) {
    ...
    });



  • drag

    Type:
    dialogdrag
    This event is triggered when the dialog is dragged.

    Code examples

    Supply a callback function to handle the drag event as an init option.
    $( ".selector" ).dialog({
    drag: function(event, ui) { ... }
    });
    Bind to the drag event by type: dialogdrag.
    $( ".selector" ).bind( "dialogdrag", function(event, ui) {
    ...
    });



  • dragStop

    Type:
    dialogdragstop
    This event is triggered after the dialog has been dragged.

    Code examples

    Supply a callback function to handle the dragStop event as an init option.
    $( ".selector" ).dialog({
    dragStop: function(event, ui) { ... }
    });
    Bind to the dragStop event by type: dialogdragstop.
    $( ".selector" ).bind( "dialogdragstop", function(event, ui) {
    ...
    });



  • resizeStart

    Type:
    dialogresizestart
    This event is triggered at the beginning of the dialog being resized.

    Code examples

    Supply a callback function to handle the resizeStart event as an init option.
    $( ".selector" ).dialog({
    resizeStart: function(event, ui) { ... }
    });
    Bind to the resizeStart event by type: dialogresizestart.
    $( ".selector" ).bind( "dialogresizestart", function(event, ui) {
    ...
    });



  • resize

    Type:
    dialogresize
    This event is triggered when the dialog is resized. demo

    Code examples

    Supply a callback function to handle the resize event as an init option.
    $( ".selector" ).dialog({
    resize: function(event, ui) { ... }
    });
    Bind to the resize event by type: dialogresize.
    $( ".selector" ).bind( "dialogresize", function(event, ui) {
    ...
    });



  • resizeStop

    Type:
    dialogresizestop
    This event is triggered after the dialog has been resized.

    Code examples

    Supply a callback function to handle the resizeStop event as an init option.
    $( ".selector" ).dialog({
    resizeStop: function(event, ui) { ... }
    });
    Bind to the resizeStop event by type: dialogresizestop.
    $( ".selector" ).bind( "dialogresizestop", function(event, ui) {
    ...
    });



  • close

    Type:
    dialogclose
    This event is triggered when the dialog is closed.

    Code examples

    Supply a callback function to handle the close event as an init option.
    $( ".selector" ).dialog({
    close: function(event, ui) { ... }
    });
    Bind to the close event by type: dialogclose.
    $( ".selector" ).bind( "dialogclose", function(event, ui) {
    ...
    });



Methods

  • destroy

    Signature:
    .dialog( "destroy" )
    Remove the dialog functionality completely. This will return the element back to its pre-init state.



  • disable

    Signature:
    .dialog( "disable" )
    Disable the dialog.



  • enable

    Signature:
    .dialog( "enable" )
    Enable the dialog.



  • option

    Signature:
    .dialog( "option" , optionName , [value)
    Get or set any dialog option. If no value is specified, will act as a getter.



  • option

    Signature:
    .dialog( "option" , options )
    Set multiple dialog options at once by providing an options object.



  • widget

    Signature:
    .dialog( "widget" )
    Returns the .ui-dialog element.



  • close

    Signature:
    .dialog( "close" )
    Close the dialog.



  • isOpen

    Signature:
    .dialog( "isOpen" )
    Returns true if the dialog is currently open.



  • moveToTop

    Signature:
    .dialog( "moveToTop" )
    Move the dialog to the top of the dialogs stack.



  • open

    Signature:
    .dialog( "open" )
    Open the dialog.



Theming

The jQuery UI Dialog plugin uses the jQuery UI CSS Framework to style its look and feel, including colors and background textures. We recommend using the ThemeRoller tool to create and download custom themes that are easy to build and maintain.
If a deeper level of customization is needed, there are widget-specific classes referenced within the jquery.ui.dialog.css stylesheet that can be modified. These classes are highlighed in bold below.

Sample markup with jQuery UI CSS Framework classes

<div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable ui-resizable">
   <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
      <span id="ui-dialog-title-dialog" class="ui-dialog-title">Dialog title</span>
      <a class="ui-dialog-titlebar-close ui-corner-all" href="#"><span class="ui-icon ui-icon-closethick">close</span></a>
   </div>
   <div style="height: 200px; min-height: 109px; width: auto;" class="ui-dialog-content ui-widget-content" id="dialog">
      <p>Dialog content goes here.</p>
   </div>
</div>
Note: This is a sample of markup generated by the dialog plugin, not markup you should use to create a dialog. The only markup needed for that is <div></div>.

4:03 AM by Dilip kakadiya · 0