【问题标题】:Jquery autocomplete not working MVC with Entity FrameworkJquery 自动完成不能与实体框架一起使用 MVC
【发布时间】:2018-07-20 03:18:37
【问题描述】:

我有两个模型。其中一个模型(我的 ViewModel)与表单中的文本框相关联,另一个模型与我用来自动完成文本框(V​​ieModel.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


    【解决方案1】:

    您的代码看起来不错。我看到的唯一问题是,您在 Employee 实体对象/记录上调用 ToString() 以获取标签值。由于这是要显示给用户的值,因此您可能希望在此处使用您的 FirstName 或任何字符串属性(除非您覆盖了 Employee 类中的 ToString() 方法以返回字符串版本)

    替换这个

    return Json(matching.Select(m => new
    {
        id = m.EmpNid,
        value = m.FirstName,
        label = m.ToString()
    }), JsonRequestBehavior.AllowGet);
    

    有了这个

    return Json(matching.Select(m => new
    {
        id = m.EmpNid,
        value = m.FirstName,
        label = m.FirstName +' '+m.LastName 
    }), JsonRequestBehavior.AllowGet);
    

    根据评论

    未捕获的引用错误:$ 未定义(匿名函数)

    当您在页面中定义之前尝试使用 jQuery 时,通常会发生这种情况。仔细检查以下步骤

    1. 在其他所有内容之前包含 jQuery
    2. 在 jQuery 库之后包含 jQuery UI
    3. 仅在加载依赖库 (jQuery/jQueryUI) 后执行您的页面级脚本。您可以通过在脚本部分中调用页面级脚本来完成此操作。

      @section scripts
      {
        $(function(){
      
         // Your code for initializing the auto complete goes here
      
        })
      }
      

      假设您的布局有一个称为脚本的部分,它是在加载 jQuery 和 jQuery UI 库之后定义的。

    所以在你的布局文件中,应该是这样的

    @RenderBody()
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
    @RenderSection("scripts", required: false)
    

    【讨论】:

    • 我开始在文本框中输入内容,但仍然没有任何内容。当我开始输入时,我什至在开发者控制台或网络选项卡中都没有看到任何内容,这很奇怪吗?
    • 你的控制台有错误吗?检查您的网络选项卡,看看它是否正在调用您的服务器。返回的响应是什么?
    • 它没有拨打电话或返回错误。我只是在我的 JsonResultEmployeesAutocomplete 类中设置了一个断点(我应该在询问之前完成此操作),当我开始输入时它甚至没有进入那里。
    • 实际上,在页面加载时我得到:Sales:261 Uncaught ReferenceError: $ is not defined(anonymous function) @Sales:261 这指向我的 jquery 自动完成功能的开始。编辑:经过进一步的猜测,我将 jquery.js 放在了 _Layout.cshtml 的顶部以防万一。现在我得到:Sales:263 Uncaught TypeError: $(...).autocomplete is not a function
    • 绝对是库包含和使用顺序的问题。请参阅我的更新答案。简而言之,确保在使用之前加载 jQuery。我复制并粘贴了您的代码,它运行良好。
    【解决方案2】:

    对于 MVC 架构,您必须删除已嵌入的

    @Scripts.Render("~/bundles/Jquery") 
    

    @Scripts.Render("~/bundles/Jqueryval") 
    

    从最后的所有.cshtml 文件和最后的views/Shared/_layout.cshtml 文件中,将我们的jQuery 合适的文件放在它的头部合适的.cshtmls 文件中。

    把这些文件放在头上:

    <link href="~/Content/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" type="text/css" /> 
    
    <script src="~/Scripts/jquery-1.10.2.js" type="text/javascript"></script>
    
    <script src="~/Scripts/jquery-ui-1.10.4.custom.min.js" type="text/javascript"></script>
    

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 2015-01-10
      • 1970-01-01
      • 1970-01-01
      • 2012-07-05
      • 2016-11-05
      • 2012-08-24
      • 2023-04-11
      • 1970-01-01
      相关资源
      最近更新 更多