我有一个 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);
}