Exploring the retrieved data from the AJAX/ASP.NET controller update for a fresh perspective

  • When selectbox is called, it triggers the 'getDepAndMan()' function.

  • A value is extracted from the selectbox (successful).

  • The function calls methods in the 'GetDepartmentAndManager' controller (successful).

  • The controller returns a value (successful)

    {Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable<<>f__AnonymousType6<'string, string>>}

    Result View: [0] { UserDepartament = "value is present / string", UserManager = "value is present / string" }

  • Should return to ajax and trigger 'success: function (employee data)' (successful).

  • Should assign values to the fields (not working).

  • Display an alert (successful).

  • Show alert with values (not working, shows an alert with: undefined undefined).

View:

@(Html
     .DevExtreme()
     .SelectBox()
     .DataSource(d => d
          .Mvc()
      )
     .OnValueChanged("getDepAndMan")
  )
 @(Html.DevExtreme().TextBox()
      .ID("Id_department")
      .ReadOnly(true)
  )
 @(Html.DevExtreme().TextBox()
      .ID("Id_manager")
      .ReadOnly(true)
  )

<script type="text/javascript">

    function getDepAndMan() {


        var userId = {
           nazwaValueId: $("#idName").dxSelectBox("instance").option("value")
        };

        $.ajax({

            url: "@Url.Action("GetDepartmentAndManager", "Uzytkownicy")",
            type: "POST",
            dataType: "json",
            data: {"userId": JSON.stringify(userId)},
            cache: false,
            success: function (danePracownika) {
                  $("#Id_department")
                     .dxTextBox("instance")
                     .option("value", danePracownika.UserDepartament);
                 $("#Id_manager")
                     .dxTextBox("instance")
                    .option("value", danePracownika.UserManager);

                alert(danePracownika.UserDepartament + " " + danePracownika.UserManager);
            },
            failure: function (error) {
                alert(error);

            },
            error: function (error) {
                alert(error);
            }
        });
    }
</script>


Controller:

[HttpPost]
public ActionResult GetDepartmentAndManager(string userId) 
{

  dynamic serializer = JsonConvert.DeserializeObject<IDictionary>(userId);

            var IdCzlowieka = serializer["nazwaValueId"];

            int IntIdCzlowieka = Convert.ToInt32(IdCzlowieka);

            var danePracownika = _uzytkownicyContext.Uzytkownicy.Where(x => x.Id == IntIdCzlowieka).Select(s => new
            {
                UserDepartament = s.Departament,
                UserManager = s.ManagerLogin

            });


   return Json(danePracownika);
}

return : //

[0] { UserDepartament = "value is present / string", UserManager = "value is present / string" } https://i.sstatic.net/PQLMA.png

EDIT

The question is, what seems to be the issue with the code and why isn't it functioning for me?

.

Answer №1

Upon reviewing Your GetDepartmentAndManager method, I noticed that the passed parameter userID is not being utilized:

var employeeData = ... .Where(x => x.Id == IntEmployeeId)...

The correct usage should be Where(x => x.Id == userId).

Additionally, it seems that the value being received in the controller action is not the employee ID as expected from the JavaScript code. Instead, it appears to be a stringified object { "nameValueId": ... }, which might cause issues unless properly handled on the server side. You may need to define an IModelBinder class for converting the stringified object to a usable userId value. More information on this topic is available here.

Moreover, it's advisable to maintain consistency in the programming language used throughout the project. Mixing languages, as seen in German projects, can lead to confusion and difficulties in collaborative efforts. However, if the project is intended solely for a Polish-speaking audience, this deviation may be tolerable.

Furthermore, it's recommended to avoid using HTTP POST methods for retrieving data. The conventions suggest that GET requests are suitable for data retrieval without altering the state, while POST methods are reserved for data modification and should redirect to a GET method upon completion. Additional insights on HTTP methods are provided here.

EDIT:

Upon further investigation, I noticed that the current request is sending data as a form rather than in the expected format. Although I'm not well-versed in jQuery, the request format was captured here: https://i.sstatic.net/EYnGZ.png

To resolve this issue, I adjusted the action method signature to

public ActionResult GetDepartmentAndManager([FromForm]string userId)

which resolved the issue on my end. It's possible that the functionality is working correctly for you, but this change was necessary for proper functionality. Upon inspecting the response data, it was noted that the JSON keys were converted to kebabCase instead of the expected PascalCase, leading to undefined values being returned. Confirm the properties being accessed in the code for accuracy:

alert(employeeData.userDepartment + " " + employeeData.userManager);

UPDATE:

After verification, it was determined that the server was not at fault: https://i.sstatic.net/8yUmH.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

Using Angular, implementing conditional statements within a for loop

I am currently working on a project where I have an array being looped inside a tag, using the target="_blank" attribute. The issue is that one of the elements in the array should not have this target="_blank" attribute. What would be the best course of ...

The button is converting my text to a string instead of the integer format that I require

Hello everyone, I've been grappling with this button conundrum for the last 45 minutes, and I can't seem to find a solution. I have created three different buttons in my code snippet below. (html) <div class="action"> ...

Implement auto partial page refreshing in ASP.NET without using the UpdatePanel feature

Looking to implement auto partial page refresh in asp.net without sending excessive data through UpdatePanel. Considering using a webservice called by JavaScript instead, but unsure how to trigger it automatically rather than by button click event. Many e ...

Could it be a glitch or a special functionality when JSON objects return "@" along with the field name?

My REST web service is built using Jersey version 11 (1.11). When I make a JSON request, the response I receive looks like this: { "course_name": "test1", "cid": "testMike", "start_date": "2012-03-13T00:00:00.000-04:00", "end_date": "2012- ...

Having trouble locating the OBJ file in your Three.js WebGL project?

I am attempting to load an obj file using Three.js, but despite following various tutorials and resources online, I am only met with a black screen and no error messages in the console. The console output from the LoadingManager indicates that the objects ...

Tips for updating or replacing items in a JavaScript array

Explaining what I need, here's the code snippet: Everything works smoothly when adding a product to the items array if it does not already exist (based on id). However, if it does exist, I only want to update the item. The distinction is based on the ...

Is it possible to use the .focus() event on an entire form in JQuery? If so, how

Take a look at this HTML snippet: <form ....> <textarea>....</textarea <input .... /> </form> I'm trying to set up a help section that appears when the user focuses on any form element, and disappears when they lose ...

Filter arrays in Vue.js using checkboxes

I'm currently working with vuejs and I need to implement a filtering feature for my array using checkboxes. I attempted to use v-model to filter the array based on three specific options: "Truck," "Van," or "Tx". However, I haven't been successfu ...

Guide on extracting data from a JavaScript table using Python

Looking to extract information from a table on this page: . There are a total of 18 pages, but the url remains constant for each page. My usual method involves using BeautifulSoup to scrape data from HTML pages. However, in this case, the required data is ...

Save an array of messages by making separate API calls for each one

I have a function that makes an API call to retrieve a list of message IDs. Here is the code: function getMessageList(auth) { api.users.messages.list({ auth: auth, userId: 'me', }, function(err, response) { if (er ...

Which one to use: Response JSON object or JSON.stringify()?

If I have JSON content that I want to return, what is the best way to do it? let data = { x: 'apple', y: 'banana' }; Is it better to: A) Return the object as is when sending the response with res.send(data)? B) Convert the objec ...

Having trouble sending an array with res.send() in NodeJS

My User model contains a field that stores an array of course IDs like this: "courseId" : [ "5ac1fe64cfdda22c9c27f264", "5ac207d5794f2910a04cc9fa", "5ac207d5794f2910a04cc9fa" ] Here is how my routes are set up: router.get('/:userid/vendo ...

Cloned element does not trigger on click event

When using jQuery 1.10, I encountered an issue where cloning a div containing a button with a click event defined did not retain the click event on the cloned div. I have come across similar questions multiple times, and existing solutions advise using cl ...

Retrieving POST data from AngularJS AJAX in Python FlaskExplanation: In this

Utilizing Angular's AJAX call, I am sending data to my Flask backend for natural language processing. Here is the AJAX code snippet: $scope.processText = function(){ $http({ method: "POST", url: "http://127.0.0.1:5000/processTex ...

Warning: Unhandled Promise Rejection - Alert: Unhandled Promise Rejection Detected - Attention: Deprecation Notice

Encountering the following error message: (node:18420) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined at C:\Users\ohrid\Desktop\backend2\routes\categories.js:27:24 at Layer.han ...

I'm looking for a method to retrieve a substantial amount of JSON data from a specific URL

Retrieving data from a URL using InputStream and storing it in a StringBuffer: rssUrl = new URL(url); InputStream resultStream = rssUrl.openStream(); byte[] B = new byte[8069]; for (int N; (N = resultStream.read(B)) != -1;) { String str = new String( ...

Updating an HTML Table with AJAX Technology

I'm struggling to figure out how to refresh an HTML table using AJAX. Since I'm not the website developer, I don't have access to the server-side information. I've been unable to find a way to reload the table on this specific page: I ...

The importance of XML validation, utilizing AJAX requests, and integrating PHP functionalities

When trying to send XML data from PHP to Javascript using ajax, I encountered some 'invalid xml' errors. The structure of the XML that I am sending is as follows: <response><br> <song>tdb2009-01-29s2s06</song> ...

Loading an array into script tags in real-time

I have implemented a full-screen image slider called supersized on my website, where the images and their associated details are referenced within a script tag like this: <script type="text/javascript"> jQuery(function($){ $.supersized({ ...

Exploring the world of tweets using React

While trying to retrieve tweets using the Twit package, I keep encountering error 400. I received an error message stating: "Failed to load https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterdev&count=10: Response to prefligh ...