Вы можете использовать выпадающий список Select2 (автозаполнение + комбинированный список), как показано ниже:
Вид:
@Html.DropDownListFor(m => m.StudentId, Enumerable.Empty<SelectListItem>(), "Please select", new { @class = "", /* @Value = 1*/ })
$(document).ready(function () {
var student = $("#StudentId");
//for Select2 Options: https://select2.github.io/options.html
student.select2({
language: "tr",//don't forget to add language script (select2/js/i18n/tr.js)
//dropdownParent: $('#yourModal'), //In order to make search box enabled when using Select2 on Bootstrap modal (otherwise remove "tabindex" from modal properties).
//minimumResultsForSearch: Infinity, //permanently hide the search box
minimumInputLength: 0, //for listing all records > set 0
maximumInputLength: 20, //only allow terms up to 20 characters long
multiple: false,
placeholder: "Seçiniz",
allowClear: true,
tags: false, //prevent free text entry
width: "100%",
ajax: {
url: '/Grade/StudentLookup',
dataType: 'json',
delay: 250,
data: function (params) {
return {
query: params.term, //search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.Name + " " + item.Surname
});
});
return { results: newData };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
//templateResult: formatRepo, // omitted for brevity, see the source of this page
//templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
//You can simply listen to the select2:select event to get the selected item
student.on('select2:select', onSelect)
function onSelect(evt) {
console.log($(this).val());
}
//Event example for close event
student.on('select2:close', onClose)
function onClose(evt) {
console.log('Closed…');
}
});
Контроллер:
public ActionResult Create()
{
return PartialView("_Create"); //DO NOT fill the dropdownlist in this method
}
public ActionResult StudentLookup(string query)
{
var students = repository.Students.Select(m => new StudentViewModel
{
Id = m.Id,
Name = m.Name,
Surname = m.Surname
//FullName = m.Name + " " + m.Surname //Sending "Name" and "Surname" in one parameter causes "The specified type member 'FullName' is not supported in LINQ to Entities" error!
})
//if "query" is null, get all records
.Where(m => string.IsNullOrEmpty(query) || m.Name.StartsWith(query))
.OrderBy(m => m.Name);
return Json(students, JsonRequestBehavior.AllowGet);
}
Надеюсь, это поможет ...