HTML and CSS Reference
In-Depth Information
jQuery Code
The web form also needs some jQuery code that does the following:
• Populates
<datalist>
items by fetching existing
Title
s (designations) from the
Employees
table
• Validates that an employee is at least 18 years old at the time of hiring
• Validates that telephone numbers match the US phone number format
To populate the
<datalist>
items, you need to make an Ajax call to the server and retrieve all existing
Title
values. You do so using the
$.ajax()
method, as shown in Listing 5-22.
Listing 5-22.
Populating the
<datalist>
with Existing
Title
Values
$(document).ready(function () {
$.ajax({
url: 'employeeform.aspx/GetTitles',
type: 'post',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (results) {
for (var i = 0; i < results.d.length; i++) {
$("#lstTitles").append("<option label='" + results.d[i] +
"' value='" + results.d[i] + "'></option>");
}
},
error: function (err) { alert(err.status + " - " + err.statusText); }
});
...
The
$.ajax()
method invokes a web method,
GetTitles()
, that resides in the
EmployeeForm.aspx
web
form.
GetTitles()
returns a string array of existing titles. Once the titles are returned, they're added to the
<datalist>
using the jQuery
append()
method. The
GetTitles()
web method is shown in Listing 5-23.
Listing 5-23.
GetTitles()
Web Method
[WebMethod]
public static string[] GetTitles()
{
NorthwindEntities db=new NorthwindEntities();
var data = (from item in db.Employees
select item.Title).Distinct();
return data.ToArray();
}
GetTitles()
selects distinct
Title
values from the
Employees
table and returns them to the caller as an
array. Figure 5-23 shows how the
<datalist>
looks at runtime.