Search code examples
javascriptjqueryasp.net-mvcasp.net-mvc-4jquery-ui

Jquery ui autocomplete not working in partial view


Admin controller

public ViewResult Products()

public PartialViewResult AddProduct()

public JsonResult AutoComplete(string prefix)

View

Product.cshtml

AddProduct.cshtml - Partial View

I'm loading a partial view(AddProduct.cshtml) in modal popup in main view.

In partial view I have a form and I'm trying to add jQuery UI autocomplete on input field but its not working.

$(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
        });
    });

I have added this jquery code in partial view page itself, also when I'm trying to save form data using ajax that too not working


Solution

  • Finally I was able to resolve this issue myself.

    Here is my Controller code:

    [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
    

    View

    Product.cshtml - Html for listing all the products (Main View)
    
    AddProduct.cshtml - Html for add new product form (Partial View)
    

    So I have added all the jQuery refrence in the _Layout.cshtml (shared view) file and in partial view I have added the following jQuery code at bottom of the page

    $("#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