Having trouble retrieving nested JSON values for a dropdown list

Below is some example JSON data

https://i.sstatic.net/zl3XR.png

At the moment, I am successfully able to retrieve Bank HooMan by using

var b = details.b.Select(x => x.Bank).FirstOrDefault();
when I put a breakpoint in the controller. However, my issue lies in how to select Hooman for @Html.DropDownListFor

Here is what I have attempted so far:

@Html.DropDownListFor(m => m.BankID, new SelectList(ViewBag.BankList, "BankID", "BankName", Model.b.Select(x => x.Bank).FirstOrDefault()), new { @class = "form-control" })

Unfortunately, this method does not seem to select HooMan. I have also tried utilizing SelectList on the model like this:

details.BankList = new SelectList(JsonConvert.DeserializeObject<List<BankLists>>(await OperationServices.GetBankListAsync()),
                                        "BankID", "BankName", details.b.Select(x => x.Bank).FirstOrDefault());
//View
@Html.DropDownListFor(m => m.BankID, Model.BankList, new { htmlAttributes = new { @class = "form-control" } })

However, I still encounter the same issue where the dropdownlist is unable to select the data. Is there something that I may be overlooking? Additionally, I need to access values within acs.

EDIT (as requested by Tomato32):

BankList is also in JSON format which we deserialize into a model. I can populate the list and add it to the dropdown, but I am struggling to select the value from the nested JSON mentioned above.

https://i.sstatic.net/8zXuW.png

Answer №1

Hey there, apologies for the delayed response. You have chosen BankName for the Dropdownlist, which prevents it from selecting the correct value.

You can use JQuery to set the selected value without making extensive changes to the code. Here's a helpful example. Hope this resolves your issue :))

1) Inside the controller

var selectedBank = bankData.b.Select(t => t.Bank).FirstOrDefault();  //Retrieve the selected bank name

ViewBag.SelectedBankID = banklist.FirstOrDefault(t => t.BankName == selectedBank).BankID; //Obtain the BankID 

2) In the View

<script>
        $(document).ready(function () {
            $('#BankID').val('@ViewBag.SelectedBankID');
        });
    </script>

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

Distributing utility functions universally throughout the entire React application

Is there a way to create global functions in React that can be imported into one file and shared across all pages? Currently, I have to import helper.tsx into each individual file where I want to use them. For example, the helper.tsx file exports functio ...

Having difficulty linking a click event to an Anchor tag within a React component

Here is the code snippet for ComponentA.js: This is the return statement inside the component return ( ...... <a id="MytoolTip" ...... <ComponentB content={ ` <div class="share_cart_tt ...

The Material UI dialog is causing issues for CKEditor 4

In the midst of my React project, I have incorporated CKEditor 4 into a Material UI dialog. However, when attempting to utilize advanced features like Math, I encounter an issue where I am unable to input any text into input or textarea fields. Despite sea ...

Formatting strings with positive or negative numbers can be achieved using Utilities.formatString

Looking to enhance the visual representation of numeric string data by displaying it in different colors based on whether the number is positive or negative. Current code snippet: var url = 'https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxx ...

Bookshelfjs fails to return a promise when updating multiple data

I am facing an issue when trying to update multiple rows in my database. The problem lies in the fact that the promise does not return anything, even though the data is successfully saved. Below is a snippet of my code: doUpdate: Promise.method(function ...

Utilize the fetch function within a Vuex action

After creating a store action to fetch an API, I encountered an error when trying to dispatch it from the component's created lifecycle hook. The error message displayed was 'Cannot read property 'dispatch' of undefined'. Despite r ...

My gadget is caught in a loop, the conditions are failing to function properly

I recently developed a basic web watch application using Tizen Studio specifically designed for Gear watches and similar devices. Within this web watch, I implemented 6 conditions that are intended to change the background of the watch based on the curren ...

What is the most efficient way to calculate the current percentage of time that has elapsed today

Is there a way to calculate the current time elapsed percentage of today's time using either JavaScript or PHP? Any tips on how to achieve this? ...

Error: The program could not locate the entry point for the application: WebDev.WebServer40.EXE

When attempting to run my asp.net projects connected to the server, I encountered an alert window displaying the message: "WebDev.WebServer40.EXE - Entry Point Not Found" The procedure entry point ons_subscriber_cancelcallback could not be located in th ...

Users of the website will be required to log in again after approximately 1 to 5 minutes of not being active

Recently, I took on the task of developing a website in C#, but I encountered a puzzling issue. Users of the website are being prompted to log back in after only 1-5 minutes of inactivity. I double-checked the Web.config file and confirmed that the timeout ...

Exceeding the maximum update depth can occur if a component triggers a setState function within the useEffect hook

useEffect(() => { const retrieveUserInfo = database().ref('/User/' + user.uid ).on('value', snapshot => { setComplete(snapshot.val().Complete); setUserProfile(snapshot.val().User); setStartYear(snapshot.val(). ...

Can you explain the purpose of the filters within this function and elaborate on how exactly we are achieving the return value?

Can you explain the functioning of the code snippet provided below? function areSimilar(a, b) { const ad = a.filter((v,i)=>v!=b[i]) const bd = b.filter((v,i)=>v!=a[i]) return ad.length == 0 || (ad.length == 2 && ad.join('') == bd. ...

What are the HTML5 elements that include the "load event" within their onload attribute?

Mozilla's MDN provides information regarding the load Event with this brief explanation: The load event is triggered when a resource and its dependent resources have completed loading. and references standard 1, which states Trusted Targets: ...

What are the most efficient methods to minimize the number of queries when retrieving data?

Below is a demonstration of a sample table along with a sample class: Name Parameter Value A1 P1 X A1 P2 Y A2 P1 XX A2 P2 YY Class foo { Int Name Int Value1 Int Value2 } I am seeking ...

Trouble arises when trying to insert a script tag into a live code editor using HTML

A few days ago, I successfully created a live code editor using the ace 1.2.9 library for my website guides. Now, I'm attempting to create a basic example, but when I try to enter text in the designated text area for the guides, the studio code compil ...

What is the best C# driver option for connecting to MongoDB?

I've embarked on a new project with Mongo and I'm curious about the popular opinion on which C# driver to go for? Right now, I'm thinking of going with NoRM (here) or maybe sticking with the official driver (here). Any recommendations or t ...

Unsuccessful AJAX request failing to trigger success callback

I recently encountered an issue in my .NET Core MVC application. I have included some JavaScript code within a partial view that calls a function in the controller via Ajax. However, I noticed that while the controller function is being hit, the success fu ...

Having trouble inserting a date into a MySQL database from C# code

Currently, I am utilizing C# and MySQL to work on a project. However, when attempting to insert a date from a DateTime type into the date column in the database, all I am receiving is 0000-00-00. I have attempted parsing my DateTime like this: sessionDate ...

Unresolved CORS Issue in Vue.js Using Axios with undefined Proxy Response

My attempt to retrieve data using a client vueJS on port 8080 from the REST API on port 3000 is resulting in a CORSE Error. Interestingly, a successful POST operation occurs without any issues. To resolve this error, I followed the instructions provided in ...

Issue with ASP Handler failing to send error message to ajax request in a managed hosting environment

When making an ajax call to a Handler, I am trying to return an error from a Stored Procedure in SQL. Below is the code for my ajax call: $.ajax({ url: "Handlers/MyHandlerCall.ashx?QueCtrlType=1" co ...