Updating two fields based on the returned JSON data is a straightforward process that involves extracting the

I am working with a script that makes two separate calls to different action methods and updates related fields. Here is the script:

<script type="text/javascript>
    $(document).ready(function () {
        $("#Switch_RackID").change(function () {
            var idRack = $(this).val();
            $.getJSON("/Switch/LoadDataCenterByRack", { id: idRack },
            function (RackData) {
                var select = $("#Switch_TMSRack_DataCenter_Name");
                select.empty();
                $("#Switch_TMSRack_DataCenter_Name").val(RackData.Text);
            });
            $.getJSON("/Switch/LoadZoneByRack", { id: idRack },
            function (RackData2) {
                var select = $("#Switch_TMSRack_Zone_Name");
                select.empty();
                $("#Switch_TMSRack_Zone_Name").val(RackData2.Text);
            });
        });
    });
</script>

However, I am wondering if there is a way to make a single call using getjson instead of two separate calls to update the fields. Here are my action methods:

public JsonResult LoadDataCenterByRack(int id)
{
    string datacentername = repository.FindRack(id).DataCenter.Name;
    var DCData = new { Text = datacentername, Value = datacentername };
    return Json(DCData, JsonRequestBehavior.AllowGet);
}

public JsonResult LoadZoneByRack(int id)
{
    string zonername = repository.FindRack(id).Zone.Name;
    var ZData = new { Text = zonername, Value = zonername };
    return Json(ZData, JsonRequestBehavior.AllowGet);
}

If anyone has any advice or suggestions on how to achieve this, please let me know. Thank you.

Answer №1

Absolutely, it is possible. You have the option to return an Anonymous object

To achieve this, update your controller action with the following code snippet:

public JsonResult LoadDataCenterByRack(int id)
{
    string datacenterName = repository.FindRack(id).DataCenter.Name;
    var DCData = new { Text = datacenterName, Value = datacenterName };

    string zoneName = repository.FindRack(id).Zone.Name;
    var ZData = new { Text = zoneName, Value = zoneName };

    return Json(new {
        DCData,
        ZData
    }, JsonRequestBehavior.AllowGet);
}

For the JavaScript part, use the following code snippet:

$.getJSON("/Switch/LoadDataCenterByRack", { id: idRack },
function (response) {
    $("#Switch_TMSRack_DataCenter_Name").val(response.DCData.Text);
    $("#Switch_TMSRack_Zone_Name").val(response.ZData.Text);
});

If you want to check the response in the console, utilize console.log like this:

console.log(response)

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

Implementing Autocomplete search with jQuery Chosen plugin - a step-by-step guide

CSS <select class="custom" id="company_hub" name="company_hub" style="width: 400px; display: none;"> <option>-Select Item-</option> </select> https://i.sstatic.net/x4YtN.png I attempted the following method but it was unsucces ...

What is the method to access 'let' variables in the console of a developer tool?

When you open the Chrome devtool and enter the code snippet below: // The iife is irrelevant let r = (() => { return 2; })(); and then evaluate r, the output will be: r 2 Surprisingly, both window.r and globalThis.r return undefined. Although let is ...

What is the reason that the selected/checked attributes of child select and input elements are not preserved when transferring HTML from one element to another?

In the world of jQuery, there lies a curious phenomenon. When you dare to set the HTML of one element as the HTML of another element, a strange omission occurs. The checked attribute of checkbox inputs and the selected attribute of select inputs are myster ...

Error: Failed to cast value "{ email: 'example@email.com' }" to ObjectId (type Object) for the "_id" path in the "User" model

How can I use the Mongoose ID to fetch data and send it to the client's browser? My Mongoose Database Data: {"_id":{"$oid":"6404fc0b9e6a0640b0deb716"},"username":"dddd","email":"[email&# ...

React does not display the items enclosed within the map function

I am facing an issue with rendering elements from a map function. Despite trying to modify the return statement, I have not been able to resolve the issue. class API extends Component { myTop10Artists() { Api.getMyTopArtists(function (err, data) { ...

Clicking on multiple instances of the same Vue.js component (popover) results in displaying identical data

Attempting to display an AJAX response in a popover shown by clicking an icon (a custom Vue component) brings about a challenge. The issue arises when there are multiple instances of this component, dynamically rendered through the v-for directive within a ...

Achieving a function call within a Backbone view in Backbone.js

Is it possible to call the plotPort function from the plotLoc function using this.plotPort() instead of self.plotPort()? It seems to not work for Internet Explorer when using self.plotPort(). As a workaround, I added an event to lLoca upon reset to call ...

Designing a MongoDB schema for scheduling interview time slots

I am in the process of developing a website that allows administrators to create interviews by choosing participants, start times, and end times. I have categorized the participants into two groups - Applicants and Team_Members. Initially, I considered cre ...

Merging two-dimensional arrays conditionally

I am working with 2 Arrays, arr1 = [ ['itemid-1', 'itemclass', 'timestamp'], ['itemid-2', 'itemclass', 'timestamp'], ['itemid-3', 'itemclass', 'timestamp&apos ...

What is the process for adding an image to a designated directory using multer?

As a student working on a project to develop a simple website, I am faced with the challenge of enabling users to create listings and upload pictures akin to platforms like eBay. Additionally, I aim to incorporate user profile creation where images can be ...

The deletion was not successfully carried out in the ajax request

Can anyone help with an issue I'm having while trying to remove a row from a table using the closest function? The function works fine outside of the $.post request, but it doesn't work properly when used within the post request. Here is my code: ...

Exploring the Evolution of the Internet and ASP.NET MVC Utilizing AJAX

Is it possible to store search history on a website and allow users to navigate back to previous search results by pressing the back-button? Additionally, how can we ensure that the text box is populated with the searched values? <% using(Ajax.BeginF ...

How to Send and Receive GET Requests including Parameters

When faced with the task of retrieving all records from a database based on a specific id, the process involves initiating a request from JavaScript. This request is then captured by a Servlet which accesses a DAO to query the database. Subsequently, the r ...

`The functionality of Material UI Grid item seems to be malfunctioning`

I currently have the following code snippet: <div style={{ flexGrow: 1 }}> <Grid container spacing={0} style={{ width: '100%' }}> <Grid item xs={12} sm={6}> Left Side </Grid> ...

Enhabling Effortless Button Activation & Sustained Navigation State: Integrating Dynamic Navigation in React

"I am facing a React challenge and seeking assistance to implement a specific functionality with a button. At present, the button starts with a false state, but I intend for it to automatically activate and reveal a navigation component (nav) when the ...

What is the most efficient way to import all scripts, stylesheets, and markup using just one JavaScript file?

In the realm of a fixed small snippet of code that cannot be altered after deployment (in an RIA), all elements are required to be loaded through a bootstrapper.js file: <div id="someDivID"></div> <script type="text/javascript" src="bootstr ...

Guide on implementing themes to HTML within the append() function

I am currently working on a project where I need to dynamically add HTML tags using JavaScript. However, I have noticed that the themes or styles are not being applied to the newly added elements within the append method. In my HTML file, I am using jQue ...

Using Vue.js to eliminate duplicate values from a filtered array of objects

How can I eliminate duplicate data from a v-for loop in Vue.js? I have an array of clients and another array of categories. When filtering the categories based on clientIDs, I noticed that there are duplicates present. Please choose a client from the opti ...

I want to establish the identical response output field name in NestJS by utilizing the @Expose decorator from class-transformer

My Entity definition currently looks like this: export class ItemEntity implements Item { @PrimaryColumn() @IsIn(['product', 'productVariant', 'category']) @IsNotEmpty() itemType: string; @PrimaryColumn() @IsU ...

Receiving an item in place of a true/false indicator

I wrote an asynchronous function that validates the permission status on a device. Here is the function: checkPermission = async () => { const allowed = await requestNotifications(['alert', 'sound']).then((res) => { if ...