【问题标题】:Razor autocomplete doesen't work when submitted提交时 Razor 自动完成功能不起作用
【发布时间】:2021-02-10 16:44:12
【问题描述】:

我的 Razor 项目的自动完成有一些问题。每次它返回我错误/失败。也许这甚至可能是一件愚蠢的事情,但我是 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" />

【问题讨论】:

  • 请查看我的回复,问题是否与AddAntiforgery有关,是否解决了问题?如果问题仍然存在,请尝试使用 F12 开发者工具检查是否有 JavaScript 错误?如果它解决了问题,我建议您在可以标记时尝试将其标记为该问题的已接受答案。它可以在未来帮助其他社区成员解决类似的问题。感谢您的理解。
  • 我会尽快检查,因为这周我已经搁置了项目的这一部分。

标签: javascript jquery asp.net-core asp.net-ajax razor-pages


【解决方案1】:

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

            $.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. 当返回 json 时,JSONRequestBehavior 属性应指定为 AllowGet:

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

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

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

【讨论】:

    【解决方案2】:

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

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

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

       services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
      
    2. 在Ajax beforeSend事件中,从隐藏字段中获取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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-28
      • 2020-11-14
      • 2014-03-11
      • 2014-01-16
      • 2011-03-14
      • 2013-12-23
      • 2018-01-10
      • 2016-02-24
      相关资源
      最近更新 更多