【问题标题】:Jquery ui autocomplete not working in partial viewJquery ui自动完成在部分视图中不起作用
【发布时间】:2017-06-02 14:10:08
【问题描述】:

管理员控制器

public ViewResult Products()

public PartialViewResult AddProduct()

public JsonResult AutoComplete(string prefix)

查看

Product.cshtml

AddProduct.cshtml - Partial View

我正在主视图的模态弹出窗口中加载部分视图(AddProduct.cshtml)。

在部分视图中,我有一个表单,我正在尝试在输入字段上添加 jQuery UI 自动完成功能,但它不起作用。

$(function() {
        $("#txtProductName").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: '/Admin/AutoComplete/',
                    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);
                    }
                });
            },
            minLength: 1
        });
    });

我已经在部分视图页面本身中添加了这个 jquery 代码,当我尝试使用 ajax 保存表单数据时也无法正常工作

【问题讨论】:

  • 控制台有错误吗?诸如“自动完成不是功能”或没有错误之类的东西?
  • 没有错误我已经写了console.log,但它没有在控制台中打印,所以不会触发自动完成
  • 现在我在控制台“Products:1 Uncaught TypeError: autocomplete is not a function at HTMLInputElement.onclick (Products:1)”中收到此错误
  • 你的主cshtml中是否引用了jquery-ui文件?
  • 是的,我已经包含了所有的 js 文件

标签: javascript jquery asp.net-mvc asp.net-mvc-4 jquery-ui


【解决方案1】:

终于我自己解决了这个问题。

这是我的控制器代码

[HttpGet]
public ViewResult Products() - Listing all the products (used for main view)

[HttpGet]
public PartialViewResult AddProduct() - Add new product form (used for partial view)

[HttpPost]
public JsonResult AutoComplete(string prefix) - Fetching data from database for autocomplete

查看

Product.cshtml - Html for listing all the products (Main View)

AddProduct.cshtml - Html for add new product form (Partial View)

所以我在_Layout.cshtml(共享视图)文件中添加了所有 jQuery 引用,在部分视图中我在页面底部添加了以下 jQuery 代码

$("#txtProductName").autocomplete({
    rest of the logic and ajax hit goes here...
}); - used to show autocomplete suggestion when user types

$("#AddNewProduct").on("submit", "#AddNewProductForm", function (e) {
    $.ajax({
        rest of the logic goes here...
    });
}); - used to submit the form data

【讨论】:

    猜你喜欢
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多