Home > Software design >  bind Data using json mehod and js
bind Data using json mehod and js

Time:04-26

I am trying to retrieve data to dropdownlist, using json, the program works but the dropdownlist displays a white list, by inspecting, the data is there but it is not displayed

Controller:

    public IActionResult GetClient()
    {
        var clientList = (from client in _context.Clients
                          select new SelectListItem()
                          {
                              Text = client.Nom,
                              Value = client.Id.ToString(),
                          }).ToList();

        clientList.Insert(0, new SelectListItem()
        {
            Text = "----Select----",
            Value = string.Empty
        });

        return Json(clientList);
    }

script:

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "/Clients/GetClient",
            success: function (data) {
                $.each(data, function () {
                    $("#ClientId").append($("<option></option>").val(this['Value']).html(this['Text']));

                });

            }
        });
    });
</script>

le code Html:

                </div>
                <div  asp-validation-summary="ModelOnly"></div>
                <label asp-for="ClientId"></label>
                <select asp-for="ClientId"
                        
                        asp-items="@(new SelectList(Enumerable.Empty<SelectListItem>(),"Value", "Text"))">
                </select>
            </div>

            <div>

Thanks for your help

CodePudding user response:

"The dropdownlist displays a white list, by inspecting, the data is there but it is not displayed"

The problem is very obvious. If you inspect the HTML you would be seen. The value and text in Lowercase but you have used on your code in Block/Capital uppercase that is val(this['Value']).html(this['Text'])). As you might know Json Object Keys are Lowercase - small alphabet by default.

enter image description here

Note: Just replace below snippet so that it will resolve your problem completely.

Solution:

  $("#ClientId").append($("<option></option>").val(this['value']).html(this['text']));

Output:

enter image description here

Hope it will help you accordingly to point your issue.

CodePudding user response:

Thank you very much, it works well, the objective is that each time the client is updated, the Dom updates the ddl, but this still does not work. if there is something to do in the code? I will be thankfull Regards

  • Related