Populate DropDownList on selected index change with selected using jQuery AJAX in ASP.Net MVC

akhter
 
on Nov 13, 2021 01:59 AM
Sample_110014.zip
688 Views

How to populate Dropdownlist on selected index change in MVC using entity Frame Work

I am populating dropdownlist using below code

private static List<SelectListItem> GetCategory()
{
    SilverEntities entities = new SilverEntities();
    List<SelectListItem> CategoryList = (from d in entities.Catagories
                                         select new SelectListItem
                                         {
                                             Text = d.CName,
                                             Value = SqlFunctions.StringConvert((double)d.CID)
                                         }).ToList();
 
 
 
    //Add Default Item at First Position.
    CategoryList.Insert(0, new SelectListItem { Text = "--Select Category--", Value = "" });
    return CategoryList;
}
 
private static List<SelectListItem> GetItem()
{
    SilverEntities entities = new SilverEntities();
    List<SelectListItem> ItemList = (from d in entities.ItemMasterFiles where (d.Packsize == "Bigbale")
                                     select new SelectListItem
                                     {
                                         Text = d.Descriptionitem,
                                         Value = SqlFunctions.StringConvert((double)d.CodeItem)
                                     }).ToList();
 
 
 
    //Add Default Item at First Position.
    ItemList.Insert(0, new SelectListItem { Text = "--Select Item--", Value = "" });
    return ItemList;
}
 
private static List<SelectListItem> GetSection()
{
    SilverEntities entities = new SilverEntities();
    {
        List<SelectListItem> SectionList = (from d in entities.Sections
                                            select new SelectListItem
                                            {
                                                Text = d.Secnam,
                                                Value = SqlFunctions.StringConvert((double)d.SecID)
                                            }).ToList();
        SectionList.Insert(0, new SelectListItem { Text = "--Select Section--", Value = "" }); 
        //Add Default Item at First Position. 
        return SectionList;
    }
 
}

Now i want when i select item in GetItem list then GetSection and Get Category List populate according

Means that i inserted value of Section and Category ID in ItemMasterfile.

Currently i am using webform code which is below

{
    String strQuery = "select CID,SecID From itemMasterFile where" +
                                    " itemMasterFile.CodeItem = @CodeItem and TID='2'";
    // SqlConnection con = new SqlConnection();
    SqlCommand cmde = new SqlCommand();
    cmde.Parameters.AddWithValue("@CodeItem", ddlBbitem.SelectedItem.Value);
    cmde.CommandType = CommandType.Text;
    cmde.CommandText = strQuery;
    cmde.Connection = con;
    try
    {
        con.Open();
        SqlDataReader sdr = cmde.ExecuteReader();
        while (sdr.Read())
        {
            DDLBBCID.SelectedValue = sdr[0].ToString();
            DDLBBsec.SelectedValue = sdr[1].ToString();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
        con.Dispose();
    }
}

But i want to in MVC using entityFramWork.

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Nov 22, 2021 11:48 PM

Hi akhter,

Check the below example.

Model

public class CascadingModel
{
    public int CountryId { get; set; }
    public int StateId { get; set; }
    public SelectList Countries { get; set; }
    public SelectList States { get; set; }
}

Namespaces

using System.Collections.Generic;
using System.Data.Entity.SqlServer;

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        CascadingModel model = new CascadingModel();
        model.Countries = new SelectList(PopulateCountries(), "Value", "Text");
        model.States = new SelectList(PopulateStates(), "Value", "Text");
        return View(model);
    }

    [HttpPost]
    public JsonResult GetStates(string param)
    {
        return Json(PopulateStates(Convert.ToInt32(param)));
    }

    [HttpPost]
    public ActionResult Index(int countryId, int stateId)
    {
        CascadingModel model = new CascadingModel();
        model.Countries = new SelectList(PopulateCountries(), "Value", "Text");
        model.States = new SelectList(PopulateStates(countryId), "Value", "Text");
        return View(model);
    }

    private static List<SelectListItem> PopulateCountries()
    {
        CascadingEntities entities = new CascadingEntities();
        List<SelectListItem> countries = (from d in entities.Countries
                                            select new SelectListItem
                                            {
                                                Text = d.CountryName,
                                                Value = SqlFunctions.StringConvert((double)d.CountryId)
                                            }).ToList();
        countries.Insert(0, new SelectListItem { Text = "--Select Country--", Value = "" });
        return countries;
    }

    private static List<SelectListItem> PopulateStates(int countryId = 0)
    {
        CascadingEntities entities = new CascadingEntities();
        List<SelectListItem> states = new List<SelectListItem>();
        if (countryId > 0)
        {
            states = (from d in entities.States.Where(x => x.CountryId == countryId)
                        select new SelectListItem
                        {
                            Text = d.StateName,
                            Value = SqlFunctions.StringConvert((double)d.StateId),
                            Selected = d.StateName == "Maharashtra" ? true : false // Set the selected.
                        }).ToList();
        }
        else
        {
            states = (from d in entities.States
                        select new SelectListItem
                        {
                            Text = d.StateName,
                            Value = SqlFunctions.StringConvert((double)d.StateId)
                        }).ToList();
        }
        states.Insert(0, new SelectListItem { Text = "--Select State--", Value = "" });
        return states;
    }
}

View

@model Cascading_DropDownList_MVC.Models.CascadingModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        @Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)Model.Countries, new { @class = "form-control" })
        <br />
        <br />
        @Html.DropDownListFor(m => m.StateId, (IEnumerable<SelectListItem>)Model.States, new { @class = "form-control" })
        <br />
        <br />
        <input type="submit" value="Submit" />
    }
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#CountryId').change(function () {
                var value = 0;
                if ($(this).val() != "") {
                    value = $(this).val();
                }
                $.ajax({
                    type: "POST",
                    url: "/Home/GetStates",
                    data: '{param: "' + value + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var list = response;
                        $("#StateId").empty();
                        PopulateDropDown("#StateId", list);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });

        function PopulateDropDown(dropDownId, list) {
            if (list != null && list.length > 0) {
                $(dropDownId).removeAttr("disabled");
                $.each(list, function () {
                    if (this['Selected']) {
                        $(dropDownId).append($("<option selected='selected'></option>").val(this['Value']).html(this['Text']));
                    } else {
                        $(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
                    }
                });
            }
        }

        $(function () {
            if ($('#CountryId').val() == "") {
                $("#StateId").prop("disabled", true);
            }

            if ($("#CountryId").val() != "" && $("#StateId").val() != "") {
                var message = "Country: " + $("#CountryId option:selected").text();
                message += "\nState: " + $("#StateId option:selected").text();
                alert(message);
            }
        });
    </script>
</body>
</html>

Screenshot