在自动完成文本框中显示多个值

时间:2018-07-02 07:36:13

标签: asp.net-mvc autocomplete

我正在尝试从数据库中选择名字和姓氏到mvc中的自动完成文本框中。我只能选择名字,而且效果很好。我只是不能将两个字段连接起来并在自动完成文本框中显示它。任何帮助将不胜感激

jQuery:

<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/jquery-ui.js"></script>
<script type="text/javascript">
    $(function () {
        $("#txtSearch").autocomplete({
            source: '@Url.Action("GetEngineers")'
        });
    });
</script>

 @Html.TextBox("searchTerm", null, new { id = "txtSearch" })
 <input type="submit" value="Search" class="btn btn-primary" />

控制器:

private DBEntityDataModel _context;

public EngineersController()
{
   _context = new DBEntityDataModel();
}

public JsonResult GetEngineers(string term)
{
    List<string> engineers;

    //This is working when I select just the firstname to be displayed
    //engineers = _context.tblEngineers.Where(e => e.FirstName.StartsWith(term) || (e.Surname.StartsWith(term)))
    //    .Select(n => n.FirstName).ToList();

    //var res = (from e in _context.tblEngineers
    //           where e.FirstName.ToLower().Contains(term.ToLower()) || e.Surname.ToLower().Contains(term.ToLower())
    //           select new
    //           {
    //               e.FirstName,
    //               e.Surname
    //           }).ToList();

    var res = _context.tblEngineers.Where(e => e.FirstName.StartsWith(term) || (e.Surname.StartsWith(term)))
        .Select(n => new
        {
           label = n.FirstName + ' ' + n.Surname
        }).ToList();

    return Json(res, JsonRequestBehavior.AllowGet);
}

0 个答案:

没有答案