自动完成渲染脚本不起作用

Autocomplete with rendering scripts not working

在MVC项目中,为了创建表单,我需要执行2个操作

1.validate 必填字段 - 鉴于我为此添加了以下几行

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap") 

2.for 我应该给一个字段自动完成 - 为此我在同一个 View.Scripts 中包含了 AJAX 脚本作为

 <head>

        <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

        <script src="//code.jquery.com/jquery-1.10.2.js"></script>

        <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                $("#searchString").autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            url: "/Home/searchUser",
                            type: "POST",
                            datatype: "json",
                            data: { searchString: request.term },
                            success: function (data) {

                                response($.map(data, function (item) {

                                    return { value: item.LoginName };

                                }))
                            }
                        })
                    }
                })
            })
        </script>      
    </head>

但是当我同时包含(验证和自动完成)时,自动完成不起作用。

当我评论以下行时,自动完成工作正常,验证不工作

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap") 

当上面几行没有注释时,验证工作正常,字段自动完成不工作。

您的问题可能是您未按正确顺序使用 script 文件。

请耐心尝试以下步骤。

首先从 Nuget

安装所有必需的 dependencies

1. jQuery

2. jQuery.UI

3. Bootstrap

4. Microsoft.jQuery.Unobtrusive.Ajax

5. Jquery.Validation

6. jQuery.Validation.Unobtrusive

在您的 _Layout.cshtml 视图中,所有脚本文件都应按上述顺序排列,如下所述。

创建视图模型

public class UserViewModel
{
    public int UserId { get; set; }

    [Required(ErrorMessage="Enter search text")]
    public string UserName { get; set; }

}

添加操作方法

public ActionResult Index()
{

   return View();
}



[HttpPost]
public JsonResult searchUser(string prefix)
{
   string searchTerm = prefix.ToLower();

   var dummyUsers = new[] 
     {   new { UserId = 1, UserName = "John" },
         new { UserId = 1, UserName = "Foo" },
         new { UserId = 2, UserName = "Foo2" },
         new { UserId = 3, UserName = "Bar" },
         new { UserId = 3, UserName = "Bar2" }
     }.ToList();

        // just used dummy users for demo , instead use your real database repository

    var users =  (from user in dummyUsers
                 where user.UserName.IndexOf(searchTerm, StringComparison.CurrentCultureIgnoreCase) != -1
                  select new
                  {
                     label = user.UserName,
                     val = user.UserId
                  }).ToList();

        return Json(users);
   }


    [HttpPost]
    [ValidateAntiForgeryToken()]
    public ActionResult AddUser(UserViewModel user)
    {

        return View();
    }

添加视图:

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />

</head>
<body>  

    @RenderBody()

    @*Always add scripts before closing the html body tag*@

    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

    <script type="text/javascript">
        $(function () {
            $("#txtUser").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/Home/searchUser/',
                        data: "{ 'prefix': '" + request.term + "'}",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data, function (item) {
                                return item;
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                },
                select: function (e, i) {
                    $("#hfUser").val(i.item.val);
                },
                minLength: 1
            });
        });
    </script>

</body>
</html>

Index.chtml

@model     FooDemoMvc.Models.UserViewModel

@{ 
    Layout = "~/Views/Shared/_Layout.cshtml";
}

    @using (Html.BeginForm("AddUser", "Home", FormMethod.Post,new { @class= "form-horizontal" }))
    {

        @Html.AntiForgeryToken()


        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            <label class="control-label col-sm-2">Search User:</label>
            <div class="control-label col-sm-2">
                @Html.TextBoxFor(model => model.UserName, new { id = "txtUser", @class = "form-control" })

                @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
            </div>
        </div>

            @Html.HiddenFor(model => model.UserId, new { id = "hfUser" })

            <div class="form-group">
                <div class="col-md-offset-2 col-sm-10">

                    <input type="submit" id="btnSubmit" class="btn btn-success" value="Submit" />
                </div>
            </div>



    }

注:

在此示例中,我直接在 _Layout.cshtml 中添加了 ScriptCss 文件,但您实际上可以将它们捆绑在一起以提高应用程序的性能,请检查 this.