Two Way Binding to Client Side Template Using ASP.NET AJAX 4.0

Introduction

In my previous article "Two Way Binding To Client Side Template in ASP.NET AJAX 4.0" we looked at how to bind data to a client side template. In this article we will look at how we can create some input controls and provide a list-detail (two way) kind of flow and selecting, updating and deleting the bound data to the database in AJAX 4.0 client templates.

To demonstrate the two operations in client side templates let us take ClientTemplateBindingDemoWebsite which we created in my previous article and extend it.

Selecting record in the Client Template and displaying the details

In the EmployeeUI.aspx of the website, go to the TR section of the "EmployeeTemplate" TBODY and set the sys:command attribute with value as "select" as shown in the below fig 1.0. You also set the pointer to the hand icon and provide an alternate record style to make it look good.


Fig 1.0

Now create a details section with a few input controls. The purpose of creating this section is to display the details of the selected record. Below is the HTML code:

       <h2>Detail Info</h2>
            <table id="EmployeeDetailsTemplate" class="sys-template">
                <tr>
                    <td style="width:85px">
                        ID: 
                    </td>
                    <td style="width:435px">
                        <asp:Label ID="IDLabel" Text="{binding ID}" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td style="width:85px">
                        First Name:</td>
                    <td style="width:435px">
                        <asp:TextBox ID="FirstNameTextBox" Text="{binding FirstName, mode=twoWay}" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td style="width:85px">
                        Last Name:</td>
                    <td style="width:435px">
                        <asp:TextBox ID="LastNameTextBox" Text="{binding LastName, mode=twoWay}" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td style="width:85px">
                        Age:</td>
                    <td style="width:435px">
                        <asp:TextBox ID="AgeTextBox" Text="{binding Age, mode=twoWay}" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td style="width:85px">
                        Salary:</td>
                    <td style="width:435px">
                        <asp:TextBox ID="SalaryTextBox" Text="{binding Salary, mode=twoWay}" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td style="width:85px">
                        Date Of Join:</td>
                    <td style="width:435px">
                        <asp:TextBox ID="DateOfJoinTextBox" Text="{binding JoiningDate, mode=twoWay, convert=formatDate}" runat="server"></asp:TextBox>
&nbsp;(<strong>MM/dd/yyyy</strong>)</td>
                </tr>
</table>

Set the ID of the details table as "EmployeeDetailsTable" which we will be using in the JavaScript file to provide the datasource for the input controls.

In the ClientBinding.js file let us go and do the changes for displaying the default selected index and the selected row style. Create a style called "selected" in the Default.css and below is the code:

.selected
{
    border-width:thin;
    border-style:solid;
    border-color:Black;
    background-color:Orange;
}

Below is the javascript code for the add_init event.
var dataContext;
var employeeTemplate;
Sys.Application.add_init(DisplayEmployees);

function DisplayEmployees() {
    dataContext = $create(Sys.Data.AdoNetDataContext,
                            {
                                serviceUri: "EmployeeDataService.svc"
                            });

    employeeTemplate = $create(Sys.UI.DataView,
                            {
                                dataProvider: dataContext,
                                fetchOperation: "Employees",
                                fetchParameters: { $orderby: "ID" },
                                autoFetch: true,
                                selectedItemClass: "selected",
                                initialSelectedIndex: 0
                            },
                            null,
                            null,
                            $get("EmployeeTemplate"));

    var employeeDetailsTemplate = $create(Sys.UI.DataView,
                                   null,
                                   {},
                                   null,
                                   $get("EmployeeDetailsTemplate"));

    $create(Sys.Binding,
    {
        source: employeeTemplate,
        path: "selectedData",
        target: employeeDetailsTemplate,
        targetProperty: "data"
    });
}

In the above code check the way "employeeDetailsTemplate" dataview is created from the "EmployeeDetailsTemplate" table and the binding is created by providing datasource source as employeeTemplate and target as employeeDetailsTemplate.

Fig 1.1 displays how the selected record is populated in the details section.


Fig 1.1

Also notice that when you change the data populated in the details section and tab out of the texbox notice the parent view is also updated with the changes. There are 4 binding modes available they are:

  1. Sys.BindingMode.twoWay
  2. Sys.BindingMode.oneWay
  3. Sys.BindingMode.oneWayToSource
  4. Sys.BindingMode.oneTime
  5. Sys.BindingMode.auto

TwoWay binding mode is the default one.



Two Way Binding to Client Side Template Using ASP.NET AJAX 4.0

Save Changes to database

So until now we had the input controls in the details section populated and the changes got reflected in the EmployeeListTemplate. Let's go ahead and write the code to submit the changes to the database back. In the EmployeeDetailsTemplate table add one more TR and introduce an HTML button control which will act as an action button to submit the changes.

<tr>
                    <td style="width:85px">
                        &nbsp;</td>
                    <td style="width:435px">
                        <input type="button" sys:command="update" value="Save To Database" />
                     </td>
</tr>

Notice that the attribute sys:command="update". Now get to the ClientBinding.js file and implement the event handler for updating the record. In the DisplayEmployees JavaScript function hook up the command event as shown below.

var employeeDetailsTemplate = $create(Sys.UI.DataView,
                                   null,
                                   {
                                       command: employeeCommandEventHandler
                                   },
                                   null,
                                   $get("EmployeeDetailsTemplate"));

Implement the "employeeCommandEventHandler" event, which will eventually submitting the changes.

function employeeCommandEventHandler(e, args) {
    if (args.get_commandName() === 'update') {
        dataContext.saveChanges();
    }
}

Now run the application, update the values and click on the "Save To Database" as shown in Fig 2.0 button and go and check the database for the updated value as shown in Fig 2.1.

[employee3.jpg]
Fig 2.0

[updated4.jpg]
Fig 2.1

Delete record

In this section we will go through how to delete an employee record. So let us add another button along with Save button as "Delete" button.

<tr>
                    <td style="width:85px">
                        &nbsp;</td>
                    <td style="width:435px">
                        <input type="button" sys:command="update" value="Save To Database" />
                        <input type="button" value="Delete Employee" id="deleteButton" sys:command="delete" sys:commandargument="{{$index}}" />
                    </td>
</tr>

For deleting the record we require the index of the selected record for delete. So bind the sys:commandargument with "{{$index}}" and set the sys:command="delete".

Go to the ClientBinding.js file and add the "delete code" in the employeeCommandEventHandler. Below is the code. I have inlined my comments in the code:

function employeeCommandEventHandler(e, args) {
    if (args.get_commandName() === 'update') {
        dataContext.saveChanges();
    }
    else if (args.get_commandName() === 'delete') {
        //get the index from the command argument
        var index = args.get_commandArgument();
        //Get the data form the employeeTemplate
        var employees = employeeTemplate.get_data();
        //get the employee using the index
        var employee = employees[index];
        //remove the entity employee from the list
        dataContext.removeEntity(employee);
        //submit the delete changes to the database
        dataContext.saveChanges();
        //Update the employee template with the updated data
        $find('EmployeeTemplate').fetchData(null, null, Sys.Data.MergeOption.overwriteChanges)
    }
}

Conclusion

In this article we looked at the two way binding which syncs the source and the target. We also looked into selecting, updating and deleting the records using ASP.NET AJAX 4.0. The important thing here to note is, all the above mentioned things are achieved completely on the client side and without using any ASP.NET server controls.

As I always do, I am attaching the source code which you could download and run through. Hope you enjoyed!

Related Articles





About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: May 7, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT This eSeminar will explore three popular games engines and how they empower developers to create exciting, graphically rich, and high-performance games for Android® on Intel® Architecture. Join us for a deep dive as experts describe the features, tools, and common challenges using Marmalade, App Game Kit, and Havok game engines, as well as a discussion of the pros and cons of each engine and how they fit into your development …

  • Instead of only managing projects organizations do need to manage value! "Doing the right things" and "doing things right" are the essential ingredients for successful software and systems delivery. Unfortunately, with distributed delivery spanning multiple disciplines, geographies and time zones, many organizations struggle with teams working in silos, broken lines of communication, lack of collaboration, inadequate traceability, and poor project visibility. This often results in organizations "doing the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds