One way to do this would be with the jQuery autocomplete plugin. Have text box on your form that allows search and a hidden field that stores the id. Use autocomplete via AJAX to get a list of name/id pairs returned as JSON based on the search criteria. Have the autocomplete set up to force selection from the list -- which will disallow any non-matching text in the field. When the user selects an item from the list have the result function store the associated id in the hidden field. Use the hidden field on form post to get the ID of the employee.
It might look something like:
View
$('#searchBox').autocomplete( '/Employees/Search', {
dataType: 'json',
max: 25,
minChars: 2,
cacheLength: 1,
mustMatch: true,
formatItem: function(data,i,max,value) {
return value;
},
parse: function(data) {
var array = new Array();
for (var i=0; i < data.length; i++) {
var datum = data[i];
var display = datum.FirstName + ' ' + datum.LastName;
array[array.length] = { data: datum, value: display, result: display };
}
}
});
$('#searchBox').result( function(event, data, formatted) {
if (data) {
$('#employeeID').val( data.EmployeeID );
}
});
$('form').submit( function() {
if (!$('#employeeID').val()) {
alert( 'You must select an employee before clicking submit!' );
return false;
}
});
<input type='text' id='searchBox' />
<input type='hidden' id='employeeID' name='employeeID' />
Controller:
public ActionResult Search( string q, int limit )
{
var query = db.Employees.Where( e => e.LastName.StartsWith( q ) )
.OrderBy( e => e.LastName )
.Select( e => new
{
FirstName = e.FirstName,
LastName = e.LastName,
EmployeeID = e.EmployeeID
});
if (limit > 0)
{
query = query.Take(limit);
}
return Json( query.ToList() );
}
public ActionResult SomeAction( int employeeID, ... )
{
...
}