简体   繁体   中英

search form with cascading dropdown list not working in asp.net mvc

I'm creating asp.net mvc 5 application, in that application I have module to filter results with multiple drop-down list,

results are depend on drop-downs

search form and search results showing in same view page

I've already implemented this module with help of stackoverflow community ,

in that module Its working fine for 1st dropdown but when I put multiple drop-down its become lock , no results when I click search button

在此处输入图片说明

this is model class

    public class ProductCollection
    {
        public string Product_ID { get; set; }        

        public string ProductType_ID { get; set; }
        public string Product_TypeEn { get; set; }
        public string Product_TypeAr { get; set; }

        public string ProductCategory_ID { get; set; }
        public string Product_CategoryEn { get; set; }
        public string Product_CategoryAr { get; set; }

        public string Country_ID { get; set; }
        public string Subsidary_Country { get; set; }

        public string Susidary_ID { get; set; }
        public string Susidary_NameEn { get; set; }
        public string Susidary_NameAr { get; set; }

        public string Product_Name_En { get; set; }
        public string Product_Description_En { get; set; }

        public string Product_Name_Ar { get; set; }
        public string Product_Description_Ar { get; set; }

        public string Status { get; set; }


        public string CreatedBy { get; set; }
        public Nullable<System.DateTime> CreatedDate { get; set; }
        public string UpdatedBy { get; set; }
        public Nullable<System.DateTime> UpdatedDate { get; set; }
    }

    // View models
    public class SearchVM
    {
        public string Type { get; set; }
        public string Category { get; set; }
        public string Country { get; set; }
        public string Subsidary { get; set; }
        public DateTime? Date { get; set; }
        public SelectList TypeList { get; set; }
        public SelectList CategoryList { get; set; }
        public SelectList CountryList { get; set; }
        public SelectList SubsidaryList { get; set; }
    }
    public class ProductsVM
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
    }

    // Data model  

    public class Type
    {
        public string ProductTypeID { get; set; }
        public string ProductTypeNameEn { get; set; }

   }

    public class Category
    {
        public string ProductCategoryID { get; set; }
        public string ProductCategoryNameEn { get; set; }
    }

    public class Country
    {
        public string Country_ID { get; set; }
        public string Country_Name { get; set; }
    }

    public class Subsidary
    {
        public string SubsidaryID { get; set; }
        public string SubsidaryNameEn { get; set; }
    }

this is view page

@model project_name.Models.SearchVM

@{
    ViewBag.Title = "Product_Search2";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Product Search</h2>

<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->

<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>

    <!-- CSS Includes -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

    <style type="text/css">
        table {
            width: 100%;
            margin-top: 25px;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="col-md-6 col-md-offset-3">
            <h1>Hello Stranger</h1>

            @using (Html.BeginForm())
            {
                <div class="form-group">
                    @Html.LabelFor(m => m.Type)
                    @Html.DropDownListFor(m => m.Type, Model.TypeList, "Select the type", new { @class = "form-control" })

                    @Html.LabelFor(m => m.Category)
                    @Html.DropDownListFor(m => m.Category, Model.CategoryList, "Select the category", new { @class = "form-control" })

                    @Html.LabelFor(m => m.Country)
                    @Html.DropDownListFor(m => m.Country, Model.CountryList, "Select the country", new { @class = "form-control" })

                    @Html.LabelFor(m => m.Subsidary)
                    @Html.DropDownListFor(m => m.Subsidary, Model.SubsidaryList, "Select the subsidary", new { @class = "form-control" })
                </div>

                    <button id="search" type="button" class="btn btn-success submit">Search</button>
            }

            <table>
                <thead>
                    <tr><th>ID</th><th>Product name</th><th>Category</th><th>Action</th></tr>
                </thead>
                <tbody id="table"></tbody>
            </table>

            <table id="template" style="display: none;">
                <tr><td></td><td></td><td></td><td><a>Edit</a></td></tr>
                <table>



        </div>
    </div>

    <!-- JS includes -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

    <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>

    <script type="text/javascript">

            var url = '@Url.Action("FetchProducts")';
            var editUrl = '@Url.Action("Edit")';
            var type = $('#Type');

            var template = $('#template');
            var table = $('#table');
            $('#search').click(function() {
                table.empty();
                $.getJSON(url, { type: type.val(), category: category.val(), country: country.val(), subsidary: subsidary.val()}, function (data) {
                    $.each(data, function(index, item) {
                        var clone = template.clone();
                        var cells = clone.find('td');
                        cells.eq(0).text(item.ID);
                        cells.eq(1).text(item.Name);
                        cells.eq(2).text(item.Category);
                        var href = '@Url.Action("Edit")' + '/' + item.ID;
                        cells.eq(3).children('a').attr('href', href);
                        table.append(clone.find('tr'));
                    });
                });
            });



    </script>
</body>
</html>

this is controller class

public class HomeController : Controller

    {
        public ProjectEntities db = new ProjectEntities();
        [HttpGet]
        public ActionResult Product_Search2()
        {
            var types = db.AB_ProductType.ToList();
            var categories = db.AB_ProductTypeCategory.ToList();
            var countries = db.AB_Country.ToList();
            var subsidiaries = db.AB_Subsidary.ToList();

            // ...
            SearchVM model = new SearchVM()
            {
                TypeList = new SelectList(types, "ProductTypeID", "ProductTypeNameEn"),
                CategoryList = new SelectList(categories, "ProductCategoryID", "ProductCategoryNameEn"),
                CountryList = new SelectList(countries, "Country_ID", "Country_Name"),
                SubsidaryList = new SelectList(subsidiaries, "SubsidaryID", "SubsidaryNameEn")
                // ....
            };

            return View(model);
        }


        [HttpGet]
        public JsonResult FetchProducts(string type, string category, string country, string subsidary, DateTime? date)
        {
            IEnumerable<ProductCollection> products = (from P in db.AB_Product
                                                join S in db.AB_Subsidary on P.Subsidary_ID equals S.SubsidaryID
                                                where P.Status != "Active"
                                                select new ProductCollection
                                                {
                                                    Product_ID = P.ProductID,
                                                    ProductType_ID = P.ProductTypeID,
                                                    ProductCategory_ID = P.ProductCategoryID,
                                                    Product_Name_En = P.ProductTitleEn,
                                                    Susidary_ID = P.Subsidary_ID,
                                                    Country_ID = S.Country,
                                                    CreatedDate = P.CreatedDate,
                                                    Status = P.Status

                                                }

                                      ).ToList();


            var data = products.Select(p => new
            {
                ID = p.Product_ID,
                Name = p.Product_Name_En,
                Category = p.ProductCategory_ID
            });

            return Json(data, JsonRequestBehavior.AllowGet);
        }

}

once I change $.getJSON(url, { type: type.val(), category: category.val(), country: country.val(), subsidary: subsidary.val()}, function (data) { to $.getJSON(url, { type: type.val()}, function (data) { in script in view page this one working , what wrong with my approach ?

I think you missed the rest of the variables that are category ,country ,subsidiary in script

pass the rest of the values for above fields within <script></script>

Like you passed value for Type like this var type = $('#Type'); you need pass rest of the values.

In Razor you can refer variable by giving that model property

ex: for m.Type can use as ID #Type within script

I got the point

<script type="text/javascript">

        var url = '@Url.Action("FetchProducts")';
        var editUrl = '@Url.Action("Edit")';
        var type = $('#Type');
        var category = $('#Category');
        var country = $('#Country');
        var subsidary = $('#Subsidary');

        var template = $('#template');
        var table = $('#table');
        $('#search').click(function() {
            table.empty();
            $.getJSON(url, { type: type.val(), category: category.val(), country: country.val(), subsidary: subsidary.val()}, function (data) {
                $.each(data, function(index, item) {
                    var clone = template.clone();
                    var cells = clone.find('td');
                    cells.eq(0).text(item.ID);
                    cells.eq(1).text(item.Name);
                    cells.eq(2).text(item.Category);
                    var href = '@Url.Action("Edit")' + '/' + item.ID;
                    cells.eq(3).children('a').attr('href', href);
                    table.append(clone.find('tr'));
                });
            });
        });



</script>

Are you always getting the same results regardless of what options you pick in the dropdowns? You don't appear to be doing any filtering on the results, that is why.

In the controller, you pass in the selections, then don't do anything with them. You need to add them into your "WHERE" clause.

Try this:

[HttpGet]
public JsonResult FetchProducts(string type, string category, string country, string subsidary, DateTime? date)
{
   IEnumerable<ProductCollection> products = (from P in db.AB_Product
                                    join S in db.AB_Subsidary on   P.Subsidary_ID equals S.SubsidaryID
                                    where P.Status != "Active" AND
                                          P.ProductTypeID = type AND
                                          P.ProductCategoryID = category AND
                                          P.CountryID = country AND
                                          P.SubsidaryID = subsidary AND
                                          P.Date = date
                                    select new ProductCollection
                                    {
                                        Product_ID = P.ProductID,
                                        ProductType_ID = P.ProductTypeID,
                                        ProductCategory_ID = P.ProductCategoryID,
                                        Product_Name_En = P.ProductTitleEn,
                                        Susidary_ID = P.Subsidary_ID,
                                        Country_ID = S.Country,
                                        CreatedDate = P.CreatedDate,
                                        Status = P.Status

                                    }

                          ).ToList();


    var data = products.Select(p => new
    {
        ID = p.Product_ID,
        Name = p.Product_Name_En,
        Category = p.ProductCategory_ID
    });

    return Json(data, JsonRequestBehavior.AllowGet);
}

Note : you may need to check the variable names in WHERE to make sure they match your DB structure. You may also need to play around with the conditions, right now it requires the user to pick an option from every dropdown - you may wish to only require certain options to be selected - ie allow "All" countries.


Also, you appear to be selecting everything into a ProductCollection , then immediately turning it into a new object. You can probably skip this step and bind it straight to the format you need:

[HttpGet]
public JsonResult FetchProducts(string type, string category, string country, string subsidary, DateTime? date)
{
   var data = (from P in db.AB_Product
                        join S in db.AB_Subsidary on P.Subsidary_ID equals S.SubsidaryID
                        where P.Status != "Active" AND
                              P.ProductTypeID = type AND
                              P.ProductCategoryID = category AND
                              P.CountryID = country AND
                              P.SubsidaryID = subsidary AND
                              P.Date = date
                        select new
                        {
                            ID = p.Product_ID,
                            Name = p.Product_Name_En,
                            Category = p.ProductCategory_ID
                        }

              ).ToList();



    return Json(data, JsonRequestBehavior.AllowGet);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM