渲染脚本无效的自动填充

时间:2018-03-26 05:24:17

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-3 razor

在MVC项目中,对于创建表单,我需要执行2次操作

1.验证必填字段 - 在视图中,我为此

添加了以下行
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap") 

2.对于一个字段我应该给自动完成 - 为此我在同一个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") 

如果上述行没有注释,验证工作正常,字段自动填充功能无效。

1 个答案:

答案 0 :(得分:0)

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

耐心地尝试以下步骤。

首先从dependencies

安装所有必需的Nuget

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>



    }

注意:

在此示例中,我直接在Script添加了Css_Layout.cshtml个文件,但您实际上可以将它们捆绑在一起以提高应用的效果,请检查this