How to create dynamic dropdown in mvc using jquery?

Can any one help me out in this issue?

By      08-Nov-2023    2

Solutions


Adil Shahbaz

Step 1:

Create An Action 

public ActionResult BindAccount()
        {
            Entities db = new Entities();
            var list = db.Accounts().ToList();
            return Json(list, JsonRequestBehavior.AllowGet);

        }

Step 2:

Html Elements

<div>
      <labelcontrol-label">Account</label>
       <div id="mainAccountId"></div>
</div>

 

Step 3: 

Write Jquery Function

    $(document).ready(function () {
        $("#parentSelector").unbind('change').bind('change', function () {

            var MainAccount = $("#parentSelector").val();
            if (MainAccount > 0) {
                var s = $('<select id="AccountId" name="AccountId" class = "form-control"/>');
                $.get("../../Accounting/BindAccount", { parentAccount: MainAccount }, function (data) {

                    $.each(data, function (i, item) {
                        
                        //items += "<option value=\"" + item.AccountID + "\">" + item.Title + "</option>";
                        $('<option />', { value: item.AccountID, text: item.Title }).appendTo(s);

                    });
                    $("#mainAccountId").html(s);
                })


            }
        });


    });

Your Answer

10055