Wednesday, 3 August 2016

How to bind dropdownlist in mvc using ajax

1.Firstly create function for communication with database in database access layer

 public DataSet getimgsize()
        {
          
            SqlCommand com = new SqlCommand("Select * from tbl_imagesize_master", con);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }

2. Create function in Controller that return json result

        public JsonResult getimageheight()
        {
            DataSet ds = dblayer.getimgsize();
            List<imagesize> imgsize = new List<imagesize>();
            foreach (DataRow dr in ds.Tables[0].Rows)
           {
                imgsize.Add(new imagesize
             {
                 Sr_no=Convert.ToInt32(dr["Sr_no"]),
                  height=Convert.ToInt32(dr["Height"]),
                  width=Convert.ToInt32(dr["width"])
             });
            }
            return Json(imgsize, JsonRequestBehavior.AllowGet);
        }
3. In view write fallowing ajax for bindind dropdown

<script src="~/js/jquery-1.7.1.min.js"></script>
<script>
  $.get("/Admin/Admin/getimageheight", function (data) {
        $("#txthwidth").empty();
        var v = "<option>Select</option>";
        var vh = "<option>Select</option>";
        $.each(data, function (i, v1) {
            v += "<option value='" + v1.width + "'>" + v1.width + "</option>";
        });

        $("#ddlwidth").html(v);
    });
</script>

 Dropdown:

 <select id="ddlwidth" class="form-control" name="txthwidth" required></select>

Ads Inside Post