【发布时间】:2018-07-20 03:18:37
【问题描述】:
我有两个模型。其中一个模型(我的 ViewModel)与表单中的文本框相关联,另一个模型与我用来自动完成文本框(VieModel.Name)的实体(员工)相关联。我遵循了一个教程here,但似乎无法让它工作。我也研究了谷歌。这可能是我对 Entity Framework 的新手,或者我使用的是不绑定到实体的 ViewModel 和绑定到实体的模型。
最终,我尝试从员工实体模型中的 FirstName + LastName 自动完成 ViewModel 中的名称,但现在我正在尝试 FirstName。
来自实体的模型:
public partial class Employee
{
public bool ActiveFlag { get; set; }
public int EmpNid { get; set; }
public string RecKey { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
... etc
我的 ViewModel 未绑定到实体,但使用此表单发布:
public class SalesViewModel
{
[Display(Name = "Employee Name")]
[Required(ErrorMessage = "The employee name is required")]
public string Name { get; set; }
... etc
查看:
<div class="form-group">
@Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Name,
new
{
@class = "employees-autocomplete",
data_url = Url.Action("EmployeesAutocomplete", "Employee")
})
@Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" })
</div>
</div>
我的 Jquery 在页面底部:
$(function () {
$('.employees-autocomplete').autocomplete({
minLength: 0,
source: function (request, response) {
var url = $(this.element).data('url');
$.getJSON(url, { term: request.term }, function (data) {
response(data);
})
}
});
})
我的 JsonResult 控制器:
public JsonResult EmployeesAutocomplete(string term)
{
Employee[] matching = string.IsNullOrWhiteSpace(term) ?
db.Employees.ToArray() :
db.Employees.Where(p => p.FirstName.ToUpper().StartsWith(term.ToUpper())).ToArray();
return Json(matching.Select(m => new
{
id = m.EmpNid,
value = m.FirstName,
label = m.ToString()
}), JsonRequestBehavior.AllowGet);
}
我应该在帖子中做任何事情或获取请求吗?不知道我哪里出错了。
【问题讨论】:
标签: jquery asp.net-mvc entity-framework autocomplete