Ad

Unable To Get Value From Nested JSON To Dropdownlist

Here is the sample JSON

enter image description here

Right now I am able to get Bank HooMan using var b = details.b.Select(x => x.Bank).FirstOrDefault(); if I put a breakpoint from the controller. My problem is how would I be able to select Hooman for @Html.DropDownListFor

What I tried is this

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

But it doesn't seem to select HooMan.. I also tried using SelectList on 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" } })

I have the same result. Dropdownlist was unable to select the data. Anything I am missing? I also need to get values inside acs.

EDIT (as requested by Tomato32):

BankList is also JSON the we deserialize it to a model. I can get the list and added to a dropdown, but I am not able to select the value from the nested JSON above.

enter image description here

Ad

Answer

my friend, sorry for the late response. You selected BankName for Dropdownlist so it can not select true value.

You can set selected the value by JQuery so you don't need to change much code. Here is a sample. Hope to help, my friend :))

1) In controller

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

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

2) In View

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

        });
    </script>
Ad
source: stackoverflow.com
Ad