One way to do this is with the jQuery autocomplete plugin . Have a text field in your form that allows you to search for a hidden field in which the identifier is stored. Use autocomplete through AJAX to get a list of name / identifier pairs returned as JSON based on your search criteria. Set autocomplete to force a selection from a list that prohibits any inconsistent text in the field. When the user selects an item from the list, the result function stores the corresponding identifier in a hidden field. Use the hidden field in the form message to get the employee ID.
It might look something like this:
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, ... ) { ... }
source share