Populating dropdown with JSON result - Cascading DropDown using MVC3, JQuery, Ajax, JSON

后端 未结 8 1761
长发绾君心
长发绾君心 2020-12-03 11:10

I\'ve got a cascading drop-drown using mvc. Something like, if you select a country in the first-dropdown, the states of that country in the second one should be populated a

相关标签:
8条回答
  • 2020-12-03 12:06
       <script type="text/javascript">
              $(document).ready(function () {
                  $("#ddlStateId").change(function () {
                      var url = '@Url.Content("~/")' + "Home/Cities_SelectedState";
                      var ddlsource = "#ddlStateId";
                      var ddltarget = "#ddlCityId";
                      $.getJSON(url, { Sel_StateName: $(ddlsource).val() }, function (data) {
                          $(ddltarget).empty();
                          $.each(data, function (index, optionData) {
                              $(ddltarget).append("<option value='" + optionData.Text + "'>" + optionData.Value + "</option>");
                          });
    
                      });
                  });
              });
           </script>
    
    0 讨论(0)
  • 2020-12-03 12:14

    You should consider using some client-side view engine that binds a model (in your case JSON returned from API) to template (HTML code for SELECT). Angular and React might be to complex for this use case, but JQuery view engine enables you to easily load JSON model into template using MVC-like approach:

    <script type="text/javascript">
        $(function () {
            $("select#CountryID").change(function (evt) {
    
                if ($("select#CountryID").val() != "-1") {
    
                    $.ajax({
                        url: "/Home/GetStates",
                        type: 'POST',
                        data: { CountryID: $("select#CountryID").val() },
                        success: function (response) {
                                 $("#stateID").empty();
                                 $("#stateID").view(response);
                        },
                        error: function (xhr) { alert("Something seems Wrong"); }
                    });
                }
            });
        });
    </script> 
    

    It is much cleaner that generating raw HTML in JavaScript. See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown

    0 讨论(0)
提交回复
热议问题