Filtering database records using a static dropdown list in MVC 5: A step-by-step guide

Is there a way to filter database records based on the columns QtyRecieved, QtyRecievedand Void using a static HTML dropdown list?

The QtyRecieved and QtyRecievedand column are both decimal values, while Void is a boolean.

This is what I have attempted:

@Html.DropDownList("Filter", new List<SelectListItem>

           {
              new SelectListItem{ Text="Open", Value = "0" },
              new SelectListItem{ Text="Partial", Value = "1" },
              new SelectListItem{ Text="All", Value = "2" }
           })

I have used AJAX to send the request to the controller:

$("#Filter").change(function () {
    var listval = $("select option:selected").text();
        $.ajax({
            type: "GET",
            url: "@Url.Action("Index", "MaterialRequest")",
            data: { id: listval }
        });
    });

In my controller, I have implemented an 'else if' condition to display records as follows:

When Open is selected, it should display records where QtyRecieved == QtyRequested.

When Partial is selected, it will show records where QtyRecieved < QtyRequested and Void = True.

If All is selected, then all records will be shown.

Please provide assistance with the query to filter records or suggest an alternative method to achieve this.

public ActionResult Index(string listval)
        {
            if (listval == "Open")
            {
                ViewBag.Items = db.Query<MaterialDeptItemVw>("Select mt.MaterialRequestId, mt.TDate, d.DepartmentName, it.ItemName, mt.QtyRequested, mt.Comment, mt.RecievedDateTime , u.UnitName from MaterialRequest mt INNER JOIN Department d ON mt.DepartmentId = d.DepartmentId INNER JOIN Items it ON mt.ItemId = it.ItemId INNER JOIN Units u ON it.UnitId = u.UnitId where QtyRecieved = QtyRequested");
            }
            else if (listval == "Partial")
            {
                ViewBag.Items = db.Query<MaterialDeptItemVw>("Select mt.MaterialRequestId, mt.TDate, d.DepartmentName, it.ItemName, mt.QtyRequested, mt.Comment, mt.RecievedDateTime , u.UnitName from MaterialRequest mt INNER JOIN Department d ON mt.DepartmentId = d.DepartmentId INNER JOIN Items it ON mt.ItemId = it.ItemId INNER JOIN Units u ON it.UnitId = u.UnitId where QtyRecieved < QtyRequested and Void = 0");
            }
            else if (listval == "All")
            {
                ViewBag.Items = db.Query<MaterialDeptItemVw>("Select mt.MaterialRequestId, mt.TDate, d.DepartmentName, it.ItemName, mt.QtyRequested, mt.Comment, mt.RecievedDateTime , u.UnitName from MaterialRequest mt INNER JOIN Department d ON mt.DepartmentId = d.DepartmentId INNER JOIN Items it ON mt.ItemId = it.ItemId INNER JOIN Units u ON it.UnitId = u.UnitId");
            }

            return View();
        }

Answer №1

You are facing several issues in your code:

1) The action method is declared as

public ActionResult Index(string listval)
. However, in the AJAX callback, you are passing the parameter as data: { id: listval }. This causes the AJAX call to not reach the controller action because of the mismatch in parameter names.

2) Using return View() is not suitable for AJAX requests. Instead, you should return JSON data or a partial view and update the target DOM element with the AJAX response.

To resolve these issues, you need to ensure that the parameter name matches the one passed in the AJAX data parameter and utilize return Json():

public ActionResult Index(string id)
{
    string baseQuery = @"Select mt.MaterialRequestId, mt.TDate, 
                         d.DepartmentName, it.ItemName, 
                         mt.QtyRequested, mt.Comment, 
                         mt.RecievedDateTime , u.UnitName from MaterialRequest mt 
                         INNER JOIN Department d ON mt.DepartmentId = d.DepartmentId 
                         INNER JOIN Items it ON mt.ItemId = it.ItemId 
                         INNER JOIN Units u ON it.UnitId = u.UnitId";

    switch (id)
    {
        case "Open":
            baseQuery += " where QtyRecieved = QtyRequested";
            break;

        case "Partial":
            baseQuery += " where QtyRecieved < QtyRequested and Void = 0";
            break;

        case "All":
            break;

        default: goto case "All";
    }

    var items = db.Query<MaterialDeptItemVw>(baseQuery).ToList();

    return Json(items, JsonRequestBehavior.AllowGet);
}

Update the AJAX call to handle the returned data and refresh the target DOM element:

$("#Filter").change(function () {
    var listval = $("select option:selected").text();
    $.ajax({
        type: "GET",
        url: '@Url.Action("Index", "MaterialRequest")',
        data: { id: listval },
        success: function (result) {
           $('#targetElementID').html(result);
        },
        error: function (xhr, status, err) {
           // handle errors
        }
    });
});

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

Guide to initializing the state in pinia with Typescript

I am encountering an issue while trying to add typescript to a pinia store. Any suggestions on how to resolve this problem would be appreciated. The project currently utilizes pinia:^2.0.16 and Vue:3.2.37 The error message is as follows: Type '{}&a ...

Getting PHP Variable Using jQuery

Even though I've seen similar questions asked before, none of the responses quite fit my particular situation. As a complete beginner, I welcome any extra guidance you can offer. The Challenge: My goal is to create a form on page1 that sends data t ...

Guide to crafting a reply using nestjs exception filters with nestfastify

I'm facing a challenge with writing custom HTTP responses from NestJS exception filters. Currently, I am using the Nest Fastify framework instead of Express. I have created custom exception filters to handle UserNotFoundException in the following mann ...

Convert a pandas dataframe into a JSON object with nested structures

Someone raised a similar question in a different forum, which was expertly answered by user1609452 using R. However, I believe there is more to explore with this topic. Let's consider a table (MyData) that looks like this: ID Location L_size L_co ...

Need help with functions in JavaScript?

I'm struggling with understanding some code related to javascript and angularjs. I came across this line - !function(a,b,c){}(x,y,z) - and I can't make sense of it. It's something new to me and I would appreciate any help in clarifying its p ...

Gradually appear with jQuery while maintaining current position

Exploring Display Options In my current setup, I have text that initially has a display:none property, and jQuery is applied to fadeIn() the content. The challenge lies in the fact that since the text is centered, as each word appears, the positioning on ...

I am looking to modify the ID of the select element nested within a td tag

This is the code snippet I am working with: <tr> <td class="demo"> <label>nemo#2 Gender</label> <select id="custG2" required="required"> <option>....</option> <option>M</option> ...

Testing of onClick event in a React component using styled-components with Sinon spies

Utilizing sinon to test a react component and verify that an onClick function is triggered. Struggling to target the element to click on due to the use of styled-components. Encountering this error message: The "simulate" method should only be run on ...

Making a page jump with Javascript

Welcome! Let's dive into our question. Below you'll find my script and HTML code: My Script: const resultEl = document.querySelector('.allquotes'); const pageSize = document.querySelector('select[name="page-size"]') ...

Upon sending a POST request to http://localhost:5000/getData, a 404 error (Not Found) was encountered while using axios

As a newcomer to react and node.js, I have set up a fake server running on port 5000 with an API (http://localhost:5000/getData) that contains a hardcoded array of objects. My goal is to add a new object to this API from my react frontend running on port 3 ...

A step-by-step guide on setting up a confirmation pop-up message using Gravity Forms

Has anyone attempted to implement a pop-up confirmation message in Gravity Forms? I am also looking to prevent the form from disappearing after submission. By the way, I have selected text as the confirmation type in my Gravity Form settings because I do ...

Having issues retrieving the 'Ville' property from an object using the Dropdown feature in Laravel

I'm currently working on a Laravel project and facing an issue while trying to display a list featuring the name of each country ('Ville') along with their respective state. Unfortunately, I encounter an error when attempting to access the p ...

Transmit an InkCanvas signature through a WCF request

Creating a Windows 10 UWP app that will be compatible with Windows 10 Mobile, I need to include a feature where users can provide their signatures. Currently, I have set up an InkCanvas in XAML and successfully linked it to my code behind. A crucial requi ...

Display the information from a JSON array using an alert box

Similar Question: How can I access a specific value in a nested data structure or JSON? I am trying to display data from a JSON array using the following code, but it is not working: var Content = [{ "01":[{"text":"blablablablabla","foo":"abeille ...

D3-cloud creates a beautiful mesh of overlapping words

I am encountering an issue while trying to create a keyword cloud using d3 and d3-cloud. The problem I am facing is that the words in the cloud are overlapping, and I cannot figure out the exact reason behind it. I suspect it might be related to the fontSi ...

There was an issue with the Discord.js (v12) Giveaway Command that resulted in an error stating "Error: Cannot read property 'hasPermission' of undefined"

Hey everyone, I'm trying to develop my own Discord bot and I want to add a giveaway command to it. I found an example code online that I tried to implement, but unfortunately, it's not working as expected... const ms = require('ms'); c ...

Having trouble exporting a static HTML file using Next.js

https://i.stack.imgur.com/xQj7q.pngI'm a beginner in the world of React. Recently, I completed a project where I utilized "next build && next export" in my package.json file for static HTML export. By running the npm run build command, an out folder w ...

Having trouble scrolling to the top in Flickr Search using AngularJS, the results are restricting my movement

I recently followed a tutorial on creating a Flickr Search App with AngularJS (https://www.youtube.com/watch?v=lvGAgul5QT4). I managed to show the search results on my page, but encountered an issue: I couldn't scroll all the way back up to the search ...

deciphering JSON objects based on specific keys

Struggling to complete a seemingly straightforward task has left me feeling frustrated. In the header of my HTML page, I have an external car dealer API being called. At the bottom of the page, there is another external .js file containing a series of if- ...

How can Angular hide a global component when a particular route is accessed?

Is it possible to hide a global component in Angular when a specific route is opened? For instance, consider the following code: app.component.html <app-header></app-header> <app-banner></app-banner> <!-- Global Component I w ...