Filter search results using selected region from dropdown menu

I have been attempting to retrieve the value from a dropdown list and customize the search functionality specifically for the selected field. The client should only be able to search within the chosen zone in the dropdown. I have been searching for a solution without success. Thank you for any assistance you can provide.

https://i.sstatic.net/sed2C.png

This is my controller:

public JsonResult GetSearchValue(string search,int? gvt)
{

    allsearch = db.Villes.Where(x => x.IdGouvernorat.CompareTo(gvt) == x.gouvernoratModels.IdGouvernorat.CompareTo(gvt)).Where(x => x.VilleName.Contains(search)).AsEnumerable().Select(x => new VilleModels { IdVille = x.IdVille, VilleName = x.VilleName }).ToList();

    return new JsonResult { Data = allsearch, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

This is my cshtml :

@Html.DropDownListFor(m => m.VilleId1, Model.Gouvernorat, "Gouvernorat", new { @class = "btn btn-warning btn-block btn-lg dropdown-toggle",data_toggle="dropdown", @id = "dropdownlist", style = "width:100% !important" })   <div class="form-group has-success has-feedback" style="width:100%">
                    <input type="text" class="form-control" id="searchInput" placeholder="Enter your city or postal code" style="width:100%;max-width:100%;height: 45px;">
                    <i id="Icon" class="glyphicon glyphicon-ok form-control-feedback" style="color:#7dc24b;padding-top:5px"></i>
                </div>  

My script :

  <script>
    $("#searchInput").autocomplete(
        { 
            search: function () {
                $(this).addClass('ui-autocomplete-loading');
                $('#Icon').removeClass('glyphicon glyphicon-ok form-control-feedback');},
            open: function () {
                $(this).removeClass('ui-autocomplete-loading');
                $('#Icon').addClass('glyphicon glyphicon-ok form-control-feedback');},

            source: function (request, response) {


            $.ajax({

                url: '@Url.Action("GetSearchValue", "Home")',
                datatype: "json",
                data: { 

                    gvt: document.getElementById('dropdownlist').selectedIndex(),
                    search: $("#searchInput").val()
                },
                success: function (data) {

                    if (data.length>0) {
                        response($.map(data, function (item) {


                             $(document).ready(function () {

                                $("#error").slideUp();

                        });
                            return { label: item.VilleName, value: item.VilleName };
                        }
                        )
                        );
                    }                      
                    if (data.length === 0) {

                        $(document).ready(function () {

                                $("#error").show();

                        });
                    }
                },

                error: function (xhr, status, error) {
                    alert("error");
                }

            });

        }
    });

</script>

Answer №1

After thorough investigation, I have discovered the solution to the issue at hand. There are two errors that need to be addressed - one in the Controller Code and the other in the JavaScript Script.

     public JsonResult GetSearchValue(string search,int? gvt)
    {         
        List<VilleModels> allsearch = new List<VilleModels>();        
        allsearch = db.Villes.Where(x => x.VilleName.Contains(search)).AsEnumerable().ToList();
        var localities = allsearch.Where(i=>i.IdGouvernorat == gvt).Select(x => new VilleModels { IdVille = x.IdVille, VilleName = x.VilleName }).ToList();
        return new JsonResult { Data = localities, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

JavaScript Code :

 <script>
    $("#searchInput").autocomplete(
        { 
            search: function () {
                $(this).addClass('ui-autocomplete-loading');
                $('#Icon').removeClass('glyphicon glyphicon-ok form-control-feedback');},
            open: function () {
                $(this).removeClass('ui-autocomplete-loading');
                $('#Icon').addClass('glyphicon glyphicon-ok form-control-feedback');},

            source: function (request, response) {


            $.ajax({

                url: '@Url.Action("GetSearchValue", "Home")',
                datatype: "json",
                data: { 

                    gvt: document.getElementById("dropdownlist").value,
                    search: $("#searchInput").val()
                },
                success: function (data) {

                    if (data.length>0) {
                        response($.map(data, function (item) {


                             $(document).ready(function () {

                                $("#error").slideUp();

                        });
                            return { label: item.VilleName, value: item.VilleName };
                        }
                        )
                        );
                    }                      
                    if (data.length === 0) {

                        $(document).ready(function () {

                                $("#error").show();

                        });
                    }
                },

                error: function (xhr, status, error) {
                    alert("error");
                }

            });

        }
    });

</script>

https://i.sstatic.net/Dxg7s.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Anchor tags created using JQuery will remain on the same page without redirecting

Presented below is the code I have utilized to construct the anchor tag along with its content. $('div#right-slide').html("<a href=\"http://www.XXXXXXXXXXXX.info/limited-specials/\" ><h1 id=\"specials\">Click Here ...

Guide to Dynamically Including an Element in an Array using Typescript

Encountering a type error within the <RenderFormFields formFields={formFieldsData} /> component:- Types of property 'type' are not compatible. Type 'string' cannot be assigned to type '"select"'.ts(2322) Rende ...

AWS Lambda applies quotes to create the event input

I'm encountering a problem with my Python 3.8 AWS Lambda function that is meant to handle form inputs from a web application. The data from the form inputs gets passed to the Lambda function and ends up in the event dictionary. However, lambda seems t ...

What is the best way to combine two arrays into a single array using AngularJS?

Here is a code snippet: $scope.studentDetails=[]; $scope.studentDetails=[0][id:101,name:one] [1][id:102,name:two] [2][id:103,name:three] $scope.studentMarks=[]; $scope.studentMarks=[0][id:101,marks:78] ...

I need some guidance on how to implement redirectLocation in react-router and properly handle the 301 or 302 status

We are currently in the process of deploying our website using reactjs and we have made a change where we removed a specific URL /[product]/menu and merged it into our main page /[product]. Now, we have been instructed to set up a 301 redirect for /[produc ...

UCS-2 in Node.JS: Understanding Big-Endian Byte Order

Currently, I am utilizing Node.JS. In my project, I require support for big-endian UCS-2 buffers, which is not natively offered by Node's buffers that only support little-endian format. How can I achieve this specific requirement? ...

Pressing the escape key on the keyboard will act as a shortcut to go

Is there a way to use Javascript in a browser to make the escape key on the keyboard go back? For instance, when visiting this page and clicking the "Fullscreen" link, it would be great to simply press the escape key and return to the previous page. What ...

The exclude parameter does no function properly within the dotnet test command when trying to generate test coverage data

I have a project setup like this: -my-application.sln --src ----Api ----ApplicationServices ----Domain ----Infrastructure --tests ----ApplicationServices.UnitTests ----Domain.UnitTests ----Infrastructure.UnitTests The assemblies are nam ...

Can the tooltip on c3 charts be modified dynamically?

Creating a c3 chart involves defining various properties, including a tooltip. Here is an example: generateData = () => { const x = randomNR(0, 100); const y = randomNR(0, 100); const together = x + y; return { data: { columns: [ ...

Is there a way to incorporate vue samples into an independent HTML document?

Striving to broaden my knowledge of Vue, I set out to create a page with tabs inspired by one of the Vue examples available at . However, an obvious error seems to be eluding me, as I encounter a syntax issue on the line import * as Tabs from 'vue-s ...

Vue js lacks the ability to effectively link HTML elements to corresponding JavaScript functions

I seem to be missing a crucial element in my spring boot application. I am attempting to follow the initial steps outlined in the Vue documentation to create the most basic Vue application possible. Here is what I currently have: @Controller public class ...

Removing a single object from an array of objects using MongooseJS

Hello to all the MongooseJS experts out there! I'm a newcomer to MongooseJS, and I've been trying to solve this problem for the past two days but haven't found a solution yet. Thank you in advance for any help! The Issue with My Delete me ...

Testing HTTP requests on a form click in Vue.js 2 - Let's see how

Within my component, I have the following method: methods:{ ContactUs(){ this.$http.post("/api/contact-us").then((res)=>{ ///do new stuff },(err)=>{ //do new stuff }) ...

Effective ways to position images within a card alongside a changing title

I have a requirement for displaying multiple cards with dynamic titles fetched from the backend. The challenge is to align images in a row regardless of the title length, ensuring alignment based on the longest title. Below is an illustration of what I am ...

differences in opinion between JavaScript code and browser add-ons/extensions

As the owner and developer of an e-commerce website, I find that potential customers often contact us regarding ordering issues. Upon investigation, we consistently discover that the problem is caused by JavaScript errors. We frequently check their browse ...

Having difficulty validating the field accurately with Angular.js

In order to validate the input field in accordance with the user's needs using AngularJS, I have shared my code below: <div ng-class="{ 'myError': billdata.longitude.$touched && billdata.longitude.$invalid }"> <input type ...

Accessing the outer index in a nested loop using Handlebars

Imagine I have the code below: <div> {{#each questions}} <div id="question_{{@index}}"> {{#each this.answers}} <div id="answer_{{howToGetThisIndex}}_{{@index}}"> {{this}} </div> {{/each}} </div> ...

What is causing the most recent iPhones to have issues with my Javascript code?

After analyzing my webserver logs, it appears that an iOS 14 device is categorizing one of my Javascript files as "injected". This file seems to be operating in a separate environment or namespace. As a result, any AJAX attempts made by the script fail bec ...

React Native displaying identical path

Is there a way to dynamically change routes in React Native when a button is pressed? Inside my SplashContainer component, I have the following method: handleToSignUp = () => { console.log("Running handleToSignUp") this.props.navigator.push({ ...

HAML Error: $ is not defined - Uncaught ReferenceError

I am encountering an issue with the following view: /views/admin/home/index.html.haml = render partial: 'general_tab_partial' .box.boxtab %article %h2= _('Global Reporting') .clearfix = form_tag '#', :method = ...