提交时 Razor 自动完成功能不起作用

Razor autocomplete doesen't work when submitted

我的 Razor 项目的自动完成功能出现问题。每次都是returns我error/failure。也许这甚至可能是一件愚蠢的事情,但我是 ASP 的新手,所以我很难注意到。 Javascript代码

 $(function () {
    $('#searchCliente').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '/Index?handler=Search',
                data: { "term": request.term },
                type: "POST",
                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) {
            $("#idCliente").val(i.item.val);
            $("#idFatt").val(i.item.val);
        },
        minLength: 3
    });
});

页面模型代码

public IActionResult OnPostSearch(string term)
        {

            var clientefatt = (from cliente in this.context.Arc_Anagrafiche
                               where cliente.RagioneSociale.StartsWith(term)
                               select new
                               {
                                   label = cliente.RagioneSociale,
                                   val = cliente.IdAnag
                               }).ToList();

            return new JsonResult(clientefatt);
        }

HTML代码

<input asp-for="intervento.Cliente" class="form-control" id="searchCliente" />
<input asp-for="intervento.IdClienteFatturazione" class="form-control" id="idCliente" type="hidden" />

也许你应该分配 ajax 数据类型 属性,并将“类型” 属性 从 post 更改为得到,如下所示:

            $.ajax({
            url: '/Index?handler=Search',
            data: { "term": request.term },
            datatype: 'json'
            type: "GET",
            success: function (data) {
                response($.map(data, function (item) {
                    return item;
                }))
            },
            error: function (response) {
                alert(response.responseText);
            },
            failure: function (response) {
                alert(response.responseText);
            }
        });

您还可以在模型代码中尝试以下操作之一,

  1. 当 returning json JSONRequestBehavior 属性 应指定为 AllowGet:

    return Json(new {clientefatt = clientefatt}, JsonRequestBehavior.AllowGet);
    
  2. 将Model代码方法的return类型改为JsonResult,如下

    public JsonResult OnPostSearch(string term){
     return new JsonResult(clientefatt);
    }
    

很可能是第一个选项,因为您使用的是 .net 核心,会给您一个错误“ASP.NET 核心 - 当前上下文中不存在名称 'JsonRequestBehavior'”

可能与AntiForgeryToken有关,请尝试在发送Ajax请求之前在请求头中添加XSRF-TOKEN 属性。

请参考以下示例并修改您的代码:

  1. 在ConfigureServices方法中添加AddAntiforgery()服务:

     services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
    
  2. 在AjaxbeforeSend事件中,从隐藏字段中获取RequestVerificationToken,并设置请求头:

     @page
     @model RazorPageSample.Pages.AutocompleteTestModel
    
     <form method="post">
         @Html.AntiForgeryToken()
         <input type="text" id="txtCustomer" name="label" />
         <input type="hidden" id="hfCustomer" name="val" />
         <br /><br />
         <input type="submit" value="Submit" asp-page-handler="Submit" />
         <br />
     </form> 
     @section Scripts{ 
         <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js"></script>
         <script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
         <link href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" rel="Stylesheet" type="text/css" />
         <script type="text/javascript">
             $(function () {
                 $("#txtCustomer").autocomplete({
                     source: function (request, response) {
                         $.ajax({
                             url: '/AutocompleteTest?handler=AutoComplete',
                             beforeSend: function (xhr) {
                                 xhr.setRequestHeader("XSRF-TOKEN",
                                     $('input:hidden[name="__RequestVerificationToken"]').val());
                             },
                             data: { "prefix": request.term },
                             type: "POST",
                             success: function (data) {
                                 response($.map(data, function (item) {
                                     return item;
                                 }))
                             },
                             error: function (response) {
                                 alert(response.responseText);
                             },
                             failure: function (response) {
                                 alert(response.responseText);
                             }
                         });
                     },
                     position: { collision: "flip" },
                     select: function (e, i) {
                         $("#hfCustomer").val(i.item.val);
                     },
                     minLength: 1
                 });
             });
         </script>
     }
    

.cshtml.cs 文件中的代码:

    public IActionResult OnPostAutoComplete(string prefix)
    {
        var customers = new List<Customer>()
        {
            new Customer(){ ID=101, Name="Dillion"},
            new Customer(){ID=102, Name = "Tom"},
            new Customer(){ ID=103, Name="David"}
        }; 
        return new JsonResult(customers.Where(c=>c.Name.ToLower().StartsWith(prefix.ToLower())).Select(c=> new { label = c.Name, val = c.ID }).ToList());

    }

    public class Customer
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }

然后,截图如下:

参考:jQuery AutoComplete in ASP.Net Core Razor Pages