Savior

Savior

  • NA
  • 50
  • 2.1k

Cascading Dropdown using Stored Procedure in asp.net mvc

Jun 7 2021 11:15 AM
  public class ItemController : Controller
{

    DB_ITEMEntities db = new DB_ITEMEntities();       

    public ActionResult Index()
    {
        ViewBag.catVG =new SelectList( db.SP_BIND_CATEGORY(),"CATID","CATNAME");
                   
        return View();
    }

    public JsonResult GetSubcat(int catid)
    {
       var subcat = db.SP_BIND_SUBCAT_BY_CAT(catid);
        return Json(new SelectList(subcat, "SUBCATID", "SUBCATNAME"));
       
    }
}

    <label>Category</label>
    @Html.DropDownList("ddlCat", ViewBag.catVG as SelectList,new { style = "width:100px" })

        <label>SubCategory</label>
       @Html.DropDownList("ddlSubCat", new SelectList(string.Empty, "Value", "Text"), "Please select a Sub Category", new { style = "width:100px" })


    <script type="text/javascript">

$(document).ready(function () {

    $("#ddlCat").change(function () {
        $("#ddlSubCat").empty();
        $.ajax({

            type: 'POST',

            url: '@Url.Action("GetSubcat")', 
            dataType: 'json',
            data: { id: $("#ddlCat").val() },
            success: function (subcategories) {

                $.each(subcategories, function (i, subcategory) {

                    $("#ddlSubCat").append('<option value="'
                        + subcategory.Value + '">' +
                        subcategory.Text + '</option>');
                });
            },
            error: function (ex) {
                alert('No Sub Categories Found : ' + ex);
            }
        });
        return false;
    })
});

Only the category in the dropdown is binding, But the subcategory items are not fetched on selection of category. Tried out several combinations, but **unable to fetch the subcategory**.

 


Answers (4)