Apr 6, 2016

Cascading Dropdownlist in ASPNET MVC 5

Cascading Dropdownlist in ASPNET MVC 5


Here I am showing the activities about cascading dropdownlist in  ASPNET MVC5

I have already following 3 classes


 public class Division
    {
        [Key]
        public int Id { get; set; }
        [Display(Name ="Division Name")]
        public string DivisionName { get; set; }

        public virtual ICollection<District> districts { get; set; }
    } 
 public class District
    {
        [Key]
        public int Id { get; set; }
        [Display(Name ="District Name")]
        public string DistrictName { get; set; }
        public int DivisionID { get; set;}
        [ForeignKey("DivisionID")]
        public virtual Division divisions { get; set; }
        public virtual ICollection<Thana> thanas { get; set; }
    }

public class Thana
    {
        [Key]
        public int Id { get; set; }
        [Display(Name ="Thana Name")]
        public string ThanaName { get; set; }
        public int DistrictId { get; set; }
        [ForeignKey("DistrictId")]
        public virtual District districts { get; set; }
    }
Now DBContext Class:

  public class testDbContext:DbContext
    {
        public DbSet<Division> Divisions { get; set; }
        public DbSet<District> Districts { get; set; }
        public DbSet<Thana> Thanas { get; set; }
    }


 public class AddressModel
    {
        public AddressModel()
        {
            AvailableDivisions = new List<SelectListItem>();
            AvailableDistricts = new List<SelectListItem>();
            AvailableThanas = new List<SelectListItem>();
        }
        [Display(Name = "Division")]
        public int DivisionId { get; set; }
        public IList<SelectListItem> AvailableDivisions { get; set; }
        [Display(Name = "District")]
        public int DistrictId { get; set; }
        public IList<SelectListItem> AvailableDistricts { get; set; }
        [Display(Name = "Thana")]
        public int ThanaId { get; set; }
        public IList<SelectListItem> AvailableThanas { get; set; }
    }

View:

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>District</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.DistrictName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DistrictName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.DistrictName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.divisions.DivisionName, "Division Name", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.DivisionID, new SelectList(ViewBag.DivisionId, "Id", "DivisionName"), "-- Select -- ", htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.DivisionID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@model IEnumerable<test.Models.District>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.divisions.DivisionName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.DistrictName)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.divisions.DivisionName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.DistrictName)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

</table>

Districts: 

Address:

@model test.Models.AddressModel
@{
    ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        //Dropdownlist Selectedchange event
        $("#DivisionId").change(function () {
            var selectedItem = $(this).val();
            var ddlStates = $("#DistrictId");
            var statesProgress = $("#districts-loading-progress");
            statesProgress.show();
            //$("#DistrictId").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetDistrictByDivisionId")', // we are calling json method

                dataType: 'json',

                data: { DivisionId: $("#DivisionId").val() },
               // here we are get value of selected country and passing same value
                 // as inputto json method GetStates.

                success: function (data) {
                    // states contains the JSON formatted list
                    // of states passed from the controller
                    
                    ddlStates.html("<option value=''>--Select--</option>");
                    $.each(data, function (id, option) {
                        ddlStates.append($('<option></option>').val(option.id).html(option.name));
                    });
                    statesProgress.hide();
                    //$.each(states, function (i, state) {
                    //    $("#DistrictId").append('<option value="' + state.Value + '">' +
                    //     state.Text + '</option>');
                    // here we are adding option for States

                    
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
            return false;
        })
        
    });
    
        //Dropdownlist Selectedchange event
       

</script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#DistrictId").change(function () {
            var selectedItem = $(this).val();
            var ddlStates = $("#ThanaId");
            var statesProgress = $("#thanas-loading-progress");
            statesProgress.show();
            //$("#DistrictId").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetThanaByDistrictId")', // we are calling json method

                dataType: 'json',

                data: { DistrictId: $("#DistrictId").val() },
                // here we are get value of selected country and passing same value
                // as inputto json method GetStates.

                success: function (data) {
                   
                    // states contains the JSON formatted list
                    // of states passed from the controller
                    ddlStates.html("<option value=''>--Select--</option>");
                    $.each(data, function (id, option) {
                       
                        ddlStates.append($('<option></option>').val(option.id).html(option.name));
                    });
                    statesProgress.hide();
                    //$.each(states, function (i, state) {
                    //    $("#DistrictId").append('<option value="' + state.Value + '">' +
                    //     state.Text + '</option>');
                    // here we are adding option for States


                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
            return false;
        })
    });
</script>


@Html.LabelFor(model => model.DivisionId)
@Html.DropDownListFor(model => model.DivisionId, Model.AvailableDivisions)
@*@Html.DropDownList("Division", new SelectList(Model.AvailableDivisions, "DivisionId", "DivisionName"),  new { style = "width:250px", @class = "dropdown1" })*@

<br />

@Html.LabelFor(model => model.DistrictId)
@Html.DropDownListFor(model => model.DistrictId, Model.AvailableDistricts)

<span id="districts-loading-progress" style="display: none;">Please wait..</span>
<br />

@Html.LabelFor(model => model.ThanaId)
@Html.DropDownListFor(model => model.ThanaId, Model.AvailableThanas)
<span id="thanas-loading-progress" style="display: none;">Please wait..</span>

  • 0Blogger Comment
  • Facebook Comment

Leave your comment

Post a Comment