代码之家  ›  专栏  ›  技术社区  ›  Vikas

如何获取下拉的JSON对象?

  •  2
  • Vikas  · 技术社区  · 16 年前

    在尝试了更多关于级联下拉列表的内容之后,我决定通过jquery来完成它。

    这是我所在城市的控制器

    public ActionResult States(int id)  
         {
             AcademicERP.Models.AcademicERPDataContext dc = new AcademicERPDataContext();
             var states = from s in dc.States
                          where s.CountryID == id
                          select s;
             return Json(states.ToList());  
         }
    

    我想打电话给

    有脚本的城市/创建页面

        var ddlCountry;
    var ddlStateID;
    
    function pageLoad() {
        ddlStateID = $get("StateID");
        ddlCountry = $get("CountryID");
        $addHandler(ddlCountry, "change", bindOptions);
        bindOptions();
    }
     function bindOptions() {
        ddlStateID.options.length = 0;        
        var CountryID = ddlCountry.value;
        if (CountryID) {
    // some logic to call $.getJSON()
            }
    

    我看到了DD

    <%= Html.DropDownList("CountryID") %>
    <select name="StateID" id="StateID"></select>
    

    那么getjson参数是什么? 我指的是 blog . 但不起作用。

    1 回复  |  直到 16 年前
        1
  •  4
  •   Johannes Setiabudi    16 年前

    这样地:

    function bindOptions() 
    {
        ddlStateID.options.length = 0;
        var CountryID = ddlCountry.value;
        if (CountryID) 
        {
            var url = "/<YOUR CONTROLLER NAME>/States/" + CountryID;
            $.get(url, function(data) {
                // do you code to bind the result back to your drop down
            });
        }
    }
    

    或者,我将完全通过jquery使用它,而不是使用pageload:

    $(document).ready(function() {
        $("#CountryID").change(function() {
            var strCountryIDs = "";
            $("#CountryID option:selected").each(function() {
                strCountryIDs += $(this)[0].value;
            });
    
            var url = "/<YOUR CONTROLLER NAME>/States/" + strCountryIDs;
            $.getJSON(url, null, function(data) {
                $("#StateID").empty();
                $.each(data, function(index, optionData) {
                    $("#StateID").append("<option value='" 
                        + optionData.StateID 
                        + "'>" + optionData.StateName 
                        + "</option>");
                });
            });
        });
    });
    

    像这样…