Angular JS appears to be failing to properly establish values in the Dropdownlist

I have a project requirement to connect a dropdownlist with MVC and angular JS.

Here is my attempt:

var app1 = angular.module('Assign', [])
app1.controller('SAPExecutive_R4GState', function ($scope, $http, $window) {
   // alert(UMSLocationDetails);
    var LocObj = JSON.parse(UMSLocationDetails)
    var ZoneValue = "";
    $.each(LocObj, function (index, element) {
        ZoneValue += element.LocationID + ",";
    });

    ZoneValue = ZoneValue.substr(0, ZoneValue.length - 1);
    var Values = { "MaintZones": ZoneValue };

    alert(JSON.stringify(Values));

    $scope.DefaultLabel = "Loading.....";
    $http({
        method: "POST",
        url: "/App/GetR4GStates",
        dataType: 'json',
        data: JSON.stringify(Values),
        headers: { "Content-Type": "application/json" }

    }).success(function (result) {
        $scope.DefaultLabel = "--Select--";
        $scope.State = data;
    });

    post.error(function (data, status) {
        $window.alert(data.Message);
    });
});
<select id="SAPExecutive_R4GState" class="form-control" ng-model="R4GState.Selected" ng-controller="SAPExecutive_R4GState as R4GState" ng-init="Select" ng-options="b for b in list">
                                    </select>

And here is my C# code:

[HttpPost]
    public JsonResult GetR4GStates(string MaintZones)
    {
        List<SelectListItem> lstR4GState = new List<SelectListItem>();
        try
        {         
            Filters ObjFilter = new Filters();
            DataTable dt = ObjFilter.GetR4GState(MaintZones);
            if (dt.Rows.Count > 0)
            {
                lstR4GState = (from DataRow dr in dt.Rows
                               select new SelectListItem()
                               {
                                   Text = Convert.ToString(dr["R4GSTATENAME"]),
                                   Value = Convert.ToString(dr["R4GSTATECODE"])

                               }).ToList();
            }
            else
            {

                SelectListItem slEmptyData = new SelectListItem();
                slEmptyData.Text = "No Data found";
                slEmptyData.Value = "No Data found";
                lstR4GState.Add(slEmptyData);
            }
        }
        catch (Exception e)
        {
        }
        // ErrorLog.HandleErrorLog("", "", "GetR4GStates", "Error2");
        return Json(lstR4GState);
    }

Although I am receiving values in return Json(lstR4GState);, they are not populating the dropdown.

I would appreciate any guidance on where I might be making mistakes, especially since I am still learning AngularJS.

Answer №1

When working with AngularJS version greater than 1.5, it is recommended to use THEN and CATCH. Here is an example of how to do so:

angular.module('Assign', [])
  .controller('SAPExecutive_R4GState', function($scope, $http, $window) {
    const payload = {};
    $http.get('https://dog.ceo/api/breeds/list/all', payload)
      .then(function(response) {
        // Please be aware RESPONSE contains the whole response.
        // You probably want RESPONSE.DATA
        console.log(response.data);
      })
      .catch(function(err) {
        // do something with err message 
      });
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="Assign" ng-controller="SAPExecutive_R4GState"></div>

Please note that this example uses a GET request to demonstrate that it works. In a GET request, the payload will be added as a querystring. If you change it to $http.post, the payload will be included in the body of the request.

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

Using React to simulate API calls outside of testing environments

For instance, I encounter issues when certain endpoints are inaccessible or causing errors, but I still need to continue developing. An example scenario is with a function like UserService.getUsers where I want to use fake data that I can define myself. I ...

Incorrect format for a date in AngularJS

I have a time input field where I am receiving the date and time format 'Thu Jan 01 1970 12:59:00 GMT+0530 (India Standard Time)', but I only want to display the time. Is there an issue with the time picker in AngularJS? Can anyone help me resolv ...

The toggle for hiding and showing, along with changing the button color, is not functioning properly due to

I'm encountering a puzzling issue with a toggle that hides and displays information and changes color on click. The functionality works flawlessly on the page where I initially wrote the code. For instance, the button's background shifts colors w ...

Using jSLint in combination with Angular leads to an unexpected error regarding the variable "$scope"

When performing a jSLint check on my Angular-based app, I encountered an "Unexpected '$scope'" error. To replicate the issue, you can try inputting the code snippet below into jslint.com. I'm puzzled as to why the first function declaration ...

Can you show me a comprehensive list of all the REST endpoints for Express mounted Apps?

When working with Express 4, you can utilize the app._router.stack object to list your app routes. In one of the routes in my todos module routes file, I attempted to display this object by sending it as part of the response: exports.update = (req,res) = ...

Navigating fluently in React Native applications

Struggling to grasp the proper implementation of navigation in RN? The provided code snippet should shed light on the current scenario. HeaderConnected is equipped with a menu button component that utilizes a custom navigate prop for opening the Drawer me ...

Generating an array of objects based on a specified condition

I am working on creating an array of objects. I want to add objects based on a condition, but instead of not adding the object in the array, it is adding false. I have attempted the following: const flag = false; const list = [ { key: 'abc&a ...

"Responding to an Ajax request with a .NET Core server by sending an xlsx

My web application exclusively supports .xlsx files. I have implemented a function in my controller that converts .xls files to .xlsx format successfully. When trying to open a .xls file, I send it via an Ajax request. However, the converted .xlsx file do ...

Leveraging the capabilities of the Freshdesk API

Has anyone had any experience utilizing the FRESHDESK API specifically for creating tickets? The documentation states the following: Request URL: domain_URL/helpdesk/tickets.xml Request method: POST <helpdesk_ticket> <description>Disk fai ...

Template Function Problem Detected in AngularJS Formatting

I'm struggling to incorporate my scope attributes into a template function within my custom directive. The formatting for the return section in my template is not working as expected. This is how it currently looks: angular .module(' ...

Issue with Webpack throwing 'window undefined' persists despite using the 'use client' configuration in React/Next.js

I've been using Typescript 5, React 18, and Next.js 14 as my tech stack, and I keep encountering similar errors with various libraries. One of the errors I often face is ReferenceError: window is not defined. This error originates from a third-party ...

Retaining previous values in Angular reactive form during the (change) event callback

Imagine having an Angular reactive form with an input field. The goal is to keep track of the old value whenever the input changes and display it somewhere on the page. Below is a code snippet that achieves this functionality: @Component({ selector: & ...

methods for transferring information from a website to a smartphone using SMS

I am currently in the early stages of learning JavaScript and working on a project that involves creating a form (a web page) to send data to my mobile device via SMS when the submit button is clicked. However, I am unsure how to transfer data from JavaS ...

When the setDetached() function was called on an entity, it resulted in the removal of the getValidationErrors

When an entity is detached or not added to the manager, does the array of validations on the entity get destroyed? Will a newly created entity without being added to the manager lack the validation set on your model? This poses an issue for me as I am dy ...

Code snippet for a click event in JavaScript or jQuery

I initially wrote the code in JavaScript, but if someone has a better solution in jQuery, I'm open to it. Here's the scenario: I have multiple questions with corresponding answers. I want to be able to click on a question and have its answer dis ...

React - dynamically injecting external logic during execution

My goal is to modularize my React application by loading additional logic (such as containers/components) dynamically from an external .js file during runtime. For instance, I want to be able to introduce a new tab with completely different functionality o ...

The Sortable feature is functional in all browsers except for Firefox

I am currently utilizing the following example () within my asp.net application. I have successfully implemented the sortable feature in all browsers except for Firefox, where it seems to trigger the event but doesn't execute the code. $('.c ...

Retrieving JSON information from asynchronous JavaScript and XML (AJAX)

I am struggling with making a URL that contains JSON Data work properly. The issue lies in the data field - I am unsure of what to input here as it is currently undefined. My goal is to store an array of the JSON data received from the ajax request. What ...

Using AJAX to create an interactive dropdown menu with changing options

I have been working on creating a dropdown menu using Ajax. When hovering over the navigation bar, the menu successfully triggers the Ajax function to display the dropdown options. The issue arises when attempting to navigate to another page (show_activi ...

Can you share a method in javascript that extracts href= and title values, similar to PHP's preg_match_all() function?

I received an HTML string as :var code; I am looking to retrieve all the values of href and title similar to how it is done using PHP's preg_match_all(). I have achieved a similar task in PHP with the provided example but now I am curious about how I ...