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

Getting the id of a single object in a MatTable

I'm currently working on an angular 8 application where I've implemented angular material with MatTableDatasource. My goal is to retrieve the id from the selected object in my list: 0: {id: "e38e3a37-eda5-4010-d656-08d81c0f3353", family ...

Is it possible to create custom input fields using the Stripes Payment-Element?

I recently integrated Stripe into my next.js application to facilitate one-time payments. Following the standard tutorial for Stripe Elements, I created a PaymentIntent on initial render: useEffect(() => { // Create PaymentIntent as soon as the ...

Is it possible to launch a browser window using javascript?

I need to open a new Internet Explorer browser window and I am currently using the following code: window.open("http://jsc.simfatic-solutions.com", "mywindow"); However, I would like to know how can I open a new IE window with a fresh session? ...

Display a popover by making an Ajax request

When attempting to display a popover on hover of an image, I encounter an issue where the content of the popover is not being shown. This content is retrieved through an Ajax call to a template, which includes a tag used in a taglib that renders the popove ...

What is the best way to extract a JSON value and use it across multiple functions?

Currently, everything seems to be working fine. However, I'm unsure about the correct way to call the json data. I attempted using a direct link but it didn't work. Do I need to modify the "data" parameters? I'm confused because I saw that ...

retrieve a reply from a PHP script and incorporate it into JavaScript following an AJAX request

I've been working with an ajax call and everything seems to be running smoothly thanks to this script: $(document).ready(function() { $('.sortable').sortable({ stop: function(event, ui) { $(ui.item).effect("highlight"); ...

"Combining the power of JavaScript countdown with PHP date functionality

I have a JavaScript code that generates countdowns based on the user's PC date. I'm looking for a way to modify the script to use a specific timezone like: <?php date_default_timezone_set('Ireland/Dublin'); $date = date('m/d/Y ...

Integrating Asp.Net Core for server-side functionality with React for client-side interactions

I have started a simple Asp.Net default project in Visual Studio 2015 using the template: ASP.NET Core Web Application (.NET Core) / Web Application, No Authentication. Following that, I created a package.json file to load all the necessary packages for R ...

What are the steps for integrating connect-multiparty into route paths?

I am looking to incorporate connect-multiparty into my routes. Upon researching, I found the following example... var multipart = require('connect-multiparty'); var multipartMiddleware = multipart(); app.post('/upload', multipartMiddle ...

How to utilize dot notation in HTML to iterate through nested JSON in AngularJS?

I'm struggling with displaying nested objects loaded from a JSON file in Angular. I've seen examples of using dot notations in HTML to access nested data, but I'm new to Angular and can't seem to get it right. The JSON is valid, but I j ...

Loading optimized page fragments for search engines

Apologies for asking a broad question. Occasionally, I find myself loading page fragments from other pages on a website using jquery/ajax. There are various reasons for this necessity, but I am aware that content loaded via client-side ajax is not visible ...

The function .play() cannot be executed on document.getElementById(...) - it is not a

There is an error in the console indicating that document.getElementById(...).play is not a valid function. import React from 'react'; const musicComponent=(props)=>{ const style={background:props.color} return( <div classN ...

Modifying website elements with JavaScript

Can someone assist me with getting a script to work on my website that will allow me to switch between four different sets of content using buttons labeled 1, 2, 3, and 4? I have tried using addClass and removeClass but cannot seem to get it right. Here i ...

Guide on how to show the index value of an array on the console in Angular 2

Is there a way to show the array index value in the console window upon clicking the button inside the carousel component? The console seems to be displaying the index value twice and then redirecting back to the first array index value. Can we make it so ...

There seems to be an issue with Jquery not triggering the Webservice method in the Firefox browser, despite it working successfully in Chrome

Currently, I have an issue where a webservice method called via ajax in jQuery is functioning correctly in Chrome and IE browsers but not in Firefox. Here is the jQuery code: $("#btnUpdate").click(function () { var objEmp = { employeeID: $("#Em ...

Error encountered when attempting to assign a value of the original data type within the Array.reduce function

I am in the process of developing a function that takes a boolean indicator object like this: const fruits = { apple: false, banana: false, orange: false, mango: false, }; Along with an array such as ['apple', 'orange']. The go ...

Implement pop-up functionality on additional buttons. Modify existing code to accommodate multiple buttons

I have a feature that allows me to click on a button and trigger a pop-up window with the desired content. The issue I am facing is how to duplicate this functionality for multiple buttons, each triggering a different pop-up content. I attempted to duplic ...

What could be causing the issue of not being able to access an element visible in AngularJS Videogular?

I am currently working on integrating the videogular-subtitle-plugin with the most recent version of Videogular/AngularJS. As a newcomer to AngularJS, I believe there must be a simple solution that I am overlooking. My main challenge lies within a directi ...

The functionality of the jQuery script is not operating optimally, causing the expected alert to not be displayed

I implemented this jQuery script: $('input[name="add-post"]').on('click', function(form) { form.preventDefault(); for ( instance in CKEDITOR.instances ) CKEDITOR.instances[instance].updateElement(); $.ajax({ typ ...

Getting Django post_save signal to work with AJAX query

After utilizing AJAX request to create an order, I also have a post_save signal that should trigger once the order has been saved. However, it seems like this signal is not being received during the AJAX request process. Is there a way to ensure that the ...