bind Database

How to bind Database Table values to DropDownList in MVC?

—>To bind table values to dropdownlist first create table          in database with some records.

—>In view  write logic to create a label  with dropdownlist as below.

       <td>

                <label for=”State”><b>State</b></label>

                <select class=”container” id=”state” name=”stateDropdown”></select>

            </td>

—>In controller write logic as below.

[HttpGet]

        public JsonResult States()

        {

            return Json(itContext.States(), JsonRequestBehavior.AllowGet);

        }

—>In view under Script write logic as below.

  1. $(document).ready(function () {  
  2.        $.ajax({  
  3.            type: “GET”,  
  4.            url: “/State/States”,  
  5.            data: “{}”,  
  6.            success: function (data) {  
  7.                var s = ‘<option value=”-1″>Please Select a State</option>’;  
  8.                for (var i = 0; i < data.length; i++) {  
  9.                    s += ‘<option value=”‘ + data[i].StateID + ‘”>’ + data[i].Name + ‘</option>’;  
  10.                }  
  11.                $(“#state”).html(s);  
  12.            }  
  13.        });  
  14.    });  

—>Finally databasevalues bind to dropdownlist as below.

—>Link

https://www.c-sharpcorner.com/article/populating-dropown-with-ajax-call/