[RESOLVED]OnLoad Javascript is not working for DropDownList in Edit view using MVC4 C#

I have a State DropDown list and Cities DropDown List.

Only related Cities are loaded/filtered based on the selected State.

It is working for OnChage but not working for OnLoad event. 

can someone please correct my code?

Edit.cshtml

---
---
<div class="editor-label">
            @Html.LabelFor(model => model.State)
        </div>
        <div class="editor-field">
            @*@Html.DropDownList("SelectedAustraliaStateId", String.Empty)*@
            @Html.DropDownListFor(model => model.SelectedAustraliaStateId, Model.AustraliaStates, "Select a state", new { id = "States", @class = "DropDownFieldStyle" })
            @Html.ValidationMessageFor(model => model.SelectedAustraliaStateId)
        </div>


        <div class="editor-label">
            @Html.LabelFor(model => model.City)
        </div>
        <div class="editor-field">
            @*@Html.DropDownList("SelectedAustraliaCityId", String.Empty)*@
            @Html.DropDownListFor(model => model.SelectedAustraliaCityId, Model.AustraliaCities, "Select a City", new { id = "Cities", @class = "DropDownFieldStyle" })
            @Html.ValidationMessageFor(model => model.SelectedAustraliaCityId)
        </div>

script:

@section Scripts {
                    <script type="text/javascript">
                        $("#States").on("change", function () {

                            var cityDropdown = $('#Cities');
                            cityDropdown.empty();

                            $.getJSON('@Url.Action("GetCities")',
                            { id: $(this).val() },
                            function (cities) {
                                $("#Cities").append('<option value="">' + "Select a city" + '</option>');

                                $.each(cities, function (i, city) {
                                    $("#Cities").append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName + '</option>');
                                });

                            });

                            $('#Cities').show();

                        });
                    </script>

                    
                    <script type="text/javascript">
 window.onload = $("#States").on("load", function () {  //THIS IS NOT WORKING

                            var cityDropdown = $('#Cities');
                            cityDropdown.empty();

                            $.getJSON('@Url.Action("GetCities")',
                            { id: $(this).val() },
                            function (cities) {
                                $("#Cities").append('<option value="">' + "Select a city" + '</option>');

                                $.each(cities, function (i, city) {
                                    $("#Cities").append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName + '</option>');
                                });

                            });

                            $('#Cities').show();

                        });
                    </script>


                }

Once the Edit view is loaded, I want the Cities DropDown list is filtered.

Website : http://overseasindians.com.au/Accommodation/Create

Hi,

 Use this :

$( document ).ready(function() {
             var cityDropdown = $('#Cities');
             var stateDropdown = $('#States')
             cityDropdown.empty();             
             $.getJSON('@Url.Action("GetCities")',
             { id: stateDropdown.val() },
             function (cities) {
             $("#Cities").append('<option value="">' + "Select a city" + '</option>');             
             $.each(cities, function (i, city) {
              $("#Cities").append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName +                '</option>');
             });

             });

             $('#Cities').show();
});

It will run once your DOM is ready.

Thanks,

Avishek

Mark as Answer, if it helps.

Hi Avishek,

this code is not working.

its not even filtering the City DDL.

Sorry

Try this:

$( document ).ready(function() {
   var cityDropdown = $('#Cities');
   cityDropdown.empty();

   $.getJSON('@Url.Action("GetCities")',
              { id: $(this).val() },
                function (cities) {
                   $("#Cities").append('<option value="">' + "Select a city" + '</option>');

                   $.each(cities, function (i, city) {
                       $("#Cities").append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName + '</option>');
                   });

                });

                $('#Cities').show();

   
   $("#States").change(function () {

                            var cityDropdown = $('#Cities');
                            cityDropdown.empty();

                            $.getJSON('@Url.Action("GetCities")',
                            { id: $(this).val() },
                            function (cities) {
                                $("#Cities").append('<option value="">' + "Select a city" + '</option>');

                                $.each(cities, function (i, city) {
                                    $("#Cities").append('<option value="' + city.AustraliaCityId + '">' + city.AustraliaCityName + '</option>');
                                });

                            });

                            $('#Cities').show();

   });


});

for some reasons, even this is not working.

it is loading all the cities by default instead filtering

Oh, I forgot to tell you to change

id: $(this).val() },

in your first .getJSON . Just target the value of the State so the cities dropdown gets filtered on load.

//In View
 $(document).ready(function () {
            $("#ddlStateId").change(function () {

                var url = '@Url.Content("~/")' + "Area/XYZ /District_SelectedState";
                var ddlsource = "#ddlStateId";
                var ddltarget = "#ddlDistId";
                $.getJSON(url, { Sel_StateName: $(ddlsource).val() }, function (data) {
                    $(ddltarget).empty();
                    $.each(data, function (index, optionData) {
                        $(ddltarget).append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
                    });

                });
            });
        });

//Suppose In XYZ controller

  public JsonResult District_SelectedState(int Sel_StateName)
        {
            mastValueRepo = new MastValuesRepository();

            var vDistricts = mastValueRepo.GetDistNames(Sel_StateName);
            JsonResult result = new JsonResult();
            result.Data = vDistricts.ToList();
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return result;
        }

Please Check Out This Link in proper way..the area,Controller Name and Method Name

 var url = ‘@Url.Content("~/")’ + "Area/Controller /MethodName";

 var url = ‘@Url.Content("~/")’ + "Area/XYZ /District_SelectedState";

Hope This Will Help You

Leave a Reply