Ajax not firing when MVC DropDownList selection is changed

Recently delving into the world of MVC, I've been scouring for answers as to why this particular piece of code isn't functioning as intended.

Below is the snippet from my View:

$(function() {
    $("#ddlNumberOfRecords").change(function() {

        var numberOfRecords = $("#ddlNumberOfRecords").val();

        $.ajax({
            type: "POST",
            url: '@Url.Action("NumberOfRecordsChanged")',
            data: { numberOfRecords: numberOfRecords },
            success: function(returndata) {
                if (!returndata.ok) {
                    window.alert(' error : ' + returndata.message);
                } else {
                    $('#Grid').html(returndata);
                }
            }
        });
    });
});

@Html.DropDownList("ddlNumberOfRecords", Model.NumberOfRecordsSelectList)

I'm at a loss here. Can someone shed some light on what might be causing this issue? Additionally, are there any effective ways to debug this JavaScript code? I tried setting breakpoints, but they never seem to trigger.

EDIT: Below is the Action method I've created. It's quite barebones at the moment as I am solely focused on resolving the problem with the functionality. However, even with breakpoints set, it doesn't seem to be hitting the designated point.

[HttpPost]
    public ActionResult NumberOfRecordsChanged(int numberOfRecords)
    {
        return null;
    }

Answer №1

After implementing all the suggestions you provided, I can confirm that the code is working perfectly. To validate this, I created a mock-up to demonstrate its functionality.

Controller

 public ActionResult Index()
        {
            ViewModel model = new ViewModel
            {
                NumberOfRecordsSelectList = new List<SelectListItem>
                {
                   new SelectListItem
                   {
                       Selected = false,
                       Text = "one",
                       Value = "1",
                   },
                    new SelectListItem
                   {
                       Selected = false,
                       Text = "two",
                       Value = "2",
                   },
                }
            };

            return View(model);
        }

    [HttpPost]
    public ActionResult NumberOfRecordsChanged(int numberOfRecords)
    {
        return null;
    }

View

@model MvcApplication1.Models.ViewModel
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        $("#ddlNumberOfRecords").change(function() {

            var numberOfRecords = $("#ddlNumberOfRecords").val();

            $.ajax({
                type: "POST",
                url: '@Url.Action("NumberOfRecordsChanged")',
                data: { numberOfRecords: numberOfRecords },
                success: function (returndata) {
                    //No return data proviced 
                    //if (!returndata.ok) {
                    //    window.alert(' error : ' + returndata.message);
                    //} else {
                    //    $('#Grid').html(returndata);
                    //}
                }
            });
        });
    });
</script>
@Html.DropDownList("ddlNumberOfRecords", Model.NumberOfRecordsSelectList)

If you encounter any other issues, please provide details on how you are setting up your list items, the nature of the error, and any relevant information. Thank you for your assistance.

Answer №2

It looks like you're attempting to retrieve the total number of items in the dropdown list, but instead, you are fetching the value of the selected item.

In that case, you should replace this snippet...

var numberOfRecords = $("#ddlNumberOfRecords").val();

With this corrected code...

var numberOfRecords = $("#ddlNumberOfRecords option").size();

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

js categorize elements in array based on their value

Looking to organize values together that share the same value within an array [ [ [ "Mangas", 23809.132685271947 ], [ "Magazines", 2162.858571621124 ], [ "Journal", 0 ], [ "Livres", 2533.654678438289 ] ], [ [ "M ...

Lack of information occurs when sending an object to a directive within AngularJS

How can an object be passed to a directive in order to access the users data within the directive's scope? Despite attempts, I have been unsuccessful. Here is what I've done: Within my controller, I assigned an array of users to a scope: $scope ...

text area with autogrow feature shakes with each key press

Recently, I experimented with the jquery autogrow plugin that automatically adjusts the height of the text as needed. However, I encountered an issue where the bottom border of the textarea would jitter noticeably with every keystroke. I'm unsure of t ...

Organize an array of objects with underscore.js to arrange them in a

I have an array of objects that looks like this: profData=[{"Details":{"CODE":"PAT4PAS","DESCRIPTION":"PASTIE 4N20 12 X 175G","LOCATION":"FREEZER","UNITS":"BOX","WAREHOUSE":"00","AVAILABLE":"15.0000","ON_HAND":"15.0000","BRAND":"4N20","PRICE1":"18.80"," ...

Combining inheritance and isolated scopes: a comprehensive guide

I've encountered a situation where I need to sort an HTML table. Here is the code snippet: <table> <thead> <tr> <th custom-sort-one order="'Name'" >Name</th> </ ...

Using $location.path() inside of a promise

I have encountered an issue where the location is not changing after a promise is returned. function register() { firebase.auth().createUserWithEmailAndPassword($scope.email, $scope.password) .then(function (user) { console.log(user); ...

Tips for ensuring a document stays at the top of my collection when performing an update

Whenever I make changes to a document, it always ends up at the bottom of my collection. Is there a way to prevent this from happening? try { await Card.update({_id: fixedUrl}, {$push:{'comments': data}}) } catch (err) { console.log(err ...

Creating a recursive function in JavaScript to build a menu list object

Having an assortment of ['/social/swipes/women', '/social/swipes/men', '/upgrade/premium']; The objective is to create a map object that mirrors this structure: { 'social': { swipes: { wom ...

Unable to Delete Document using findOneAndDelete in Mongoose

Looking for a solution to delete a document in the database using this code: const groups = require('./groups') const ingroups = require('./ingroups') const leavegroup = await ingroups.findOne({User:message.author.id}) //Remove ...

Establishing an infoWindow for a series of markers generated within a callback function for the directionsService

I am facing a challenge with setting infoWindows for markers that are created within the callback function of a directionsService using Google Maps API V3. Despite trying various approaches, I have not been successful in achieving this task... Below is an ...

A guide on how to apply HTML attributes like checked, selected, and disabled in jQuery without providing values

This Question May Have Been Asked Before: Set attribute without value At times, when working with HTML, there is a need to assign an attribute to a DOM element without providing any specific value. For example, look at the selected parameter in this s ...

I'm stuck trying to figure out all the parameters for the MapsPage component in Angular 2

Currently, I am utilizing Angular2 with Ionic2 for my mobile app development. Everything was working flawlessly until I decided to incorporate a new module for Google Maps navigation. Specifically, I am using phonegap-launch-navigator for this purpose. The ...

What is the proper method for delivering Javascript code with rendered HTTP to a client?

During the development process, I made a decision to switch to server-side rendering in order to have better control and take advantage of other benefits. My web application relies heavily on AJAX with no url redirecting, creating a website that dynamicall ...

A guide on extracting the geometry from an STL model imported into three.js

After using STLLoader to load an STL file into three.js, I am trying to access the vertices and geometry of the model for further use. However, I am encountering difficulty in retrieving the geometry after calling the loader. How can I achieve this? Belo ...

AngularJs does not properly update the scope of a scoped directive when using ng-repeat within itself

The issue arises from calling Directive1 within the same Directive1 using ng-repeat. Although directive11 has a value in scope, when calling the nested directive with a new value, it appears to retain the initial value. I attempted to invoke the same dire ...

What sets apart a string constant from a string enclosed in quotation marks? And what techniques exist to transform one into the other?

Calling an asynchronous function: const variable = 'something' await MyAsyncFunction.execute(variable) No output is displayed. But if I change it to: await MyAsyncFunction.execute('something') It works!! Can someone please explain h ...

"Learn how to easily format specific characters in JavaScript using the text plugin to create bold text strings with a unique

I would like to transform this text into something like "|| something 1 || something 2 || more || last one ||" and then make all of that string bold by adding "|" around it then it would look like this "|| something 1 || something 2 || more || last one | ...

Unable to employ Datastore emulator on Nodejs app

Trying to integrate the datastore emulator with my nodejs application has been a challenge. Initially, I followed the guidelines provided here. Within my node application, I set up the following: var config = { projectId : "scio1-ts-datastore" } ...

typescript component parameter function causing alert

I am encountering an issue with the following code snippet: <GoogleLogin onSuccess={responseGoogle => { const { email, name } = responseGoogle.profileObj; // error: Property 'profileObj' does not exist on type 'GoogleLoginRespon ...

What could be causing the double invocation of render() in ReactNative?

I'm currently working on an app with a single screen displaying a map centered on the user's current coordinates. In my code below, I've set the latitude and longitude to null in the state of the App component. Using the componentDidMount() ...