1

我有一个 MVC Razor View 页面作为表单,供人们输入详细信息并提交到数据库。它使用下拉列表工作,但我想在表单中添加一个自动完成文本框。这很好用,但是当发回 POST 控制器时,它总是将人的 ID 设置为 0。有任何想法吗?

谢谢

Javascript:

 script type="text/javascript">

   $(document).ready(function () {
        $("#PersonName").autocomplete({
            source: '@Url.Action("AutocompleteSuggestions")',
            minLength: 2,

            select: function (event, ui) {
                if (ui.item) {
                    $("#PersonName").val(ui.item.label);
                    $("#PersonId").val(ui.item.value);
                }
            }
        });
    });
</script>

控制器:

 [HttpPost]
    public ActionResult Create(MappingModel view)
    {

        if (ModelState.IsValid)
        {
            var entity = new PersonContempancy();
            entity.PersonId = view.PersonId;
            entity.FrameworkId = view.FrameworkId;
            entity.ContempancyCategoryId = view.ContempancyCategoryId;
            entity.ContempancyId = view.ContempancyId;
            entity.ContempancyLevelId = view.ContempancyLevelId;
            entity.FrameworkLevelId = view.FrameworkLevelId;
            db.PersonContempancies.Add(entity);
            db.SaveChanges();

            return RedirectToAction("Index");  
        }



        ViewBag.Contepancies = db.Contempancies.ToList();
        ViewBag.ContempancyCategory = db.ContempancyCategories.ToList();
        ViewBag.ContempancyLevel = db.ContempancyLevels.ToList();
        ViewBag.FrameworkLevel = db.FrameworkLevels.ToList();
        ViewBag.Person = db.People.ToList();
        ViewBag.Framework = db.Frameworks.ToList();



        return View();
    }

  public ActionResult AutocompleteSuggestions(string term)
    {

        var namelist = db.People.Where(c => c.PersonName.Contains(term)).Select(c => new { value = c.PersonId, label = c.PersonName}).Distinct().Take(10);

        return Json(namelist.ToArray(), JsonRequestBehavior.AllowGet);

    }
4

1 回答 1

0

查看您的 AutoCompleteSuggestions 代码,您在返回 JSON 时似乎只发回了人名,而不是人的 ID。如果我理解正确,您需要返回名称和 ID,并通过 JQuery 在自动完成功能的选择功能中设置人员 ID。它应该(大致)看起来像这样:

var namelist = (from c in db.People where c.PersonName.Contains(term) select new { c.PersonName, c.PersonID}).Distinct().Take(10).ToArray();
return Json(namelist.ToArray(), JsonRequestBehavior.AllowGet);

     $("#searchTerm").val(ui.item.value.PersonName);
     $("#PersonID").val(ui.item.value.PersonID);
于 2012-08-09T17:18:27.837 回答