Haneef Puttur

AJAX Query to fill Select List MVC , C# asp.net

This is Proof of Concept for Querying data using AJAX and filling the drop down list from a oracle database using DB procedures.

Model :

public class listmodel
    {
        public string txtdesc{ get; set; }
        public string txtval { get; set; }
}

Controller

public JsonResult get_crn_term(string term)
        {
            var crnlist = functions.getCRN(term) as List<listmodel>;
            return Json(crnlist, JsonRequestBehavior.AllowGet);
        }

Function to Call the Oracle procedure which has the data:

  public static List<listmodel> getCRN(string term_code)
        {
            var p = new OracleDynamicParameters();
            p.Add("p_term", term_code);
            p.Add("p_crn", dbType: OracleDbType.RefCursor, direction: ParameterDirection.Output);
            var crnlist = new List<listmodel>();

            using (SqlMapper.GridReader gr = DB.GetMultiGrid("procedure.p_get_term_crn", p))
            {
                crnlist = gr.Read<listmodel>().ToList<listmodel>();
            }
            return crnlist;
        }


AJAX Script in View

 

< script >
function get_crn_data(data) {
        $.ajax({
            type: "POST",
            url: "get_crn_term",
            dataType: "json",
            data: "{ term: '" + data.value+ "'}",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                $(".crn").empty();
                var optionhtml1 = '<option value="' +
                 0 + '">' + "--Select State--" + '</option>';
                $(".crn").append(optionhtml1);
                $.each(data, function (i) {
                    var optionhtml = '<option value="' +
                data[i].txtval+ '">' +data[i].txtdesc+ '</option>';
                    $(".crn").append(optionhtml);
                });

            }})
        };
</script>

View Item
 @Html.LabelFor(model => model.crn, new { @class = “control-label col-md-2″ })

<div class=”col-md-4”>

@Html.DropDownListFor(model => model.crn, (IEnumerable<SelectListItem>)ViewData["crnData"], new { @class = "crn form-control"})
@Html.ValidationMessageFor(model => model.crn)
</div>

 .

Exit mobile version