控制器中的MVC3自动完成和POST方法

时间:2012-08-09 15:13:57

标签: c# javascript asp.net-mvc autocomplete

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

    }

1 个答案:

答案 0 :(得分:0)

查看您的AutoCompleteSuggestions代码,看起来您在返回JSON时只回发了人名,而不是该人的ID。如果我正确理解你需要返回名称和ID,并在自动完成功能的select函数中通过JQuery设置person 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);