【问题标题】:How to get the Json object for drop down?如何获取 Json 对象以进行下拉?
【发布时间】:2009-04-14 08:58:55
【问题描述】:

在对级联下拉菜单进行了更多尝试之后,我决定通过 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。但不工作。

【问题讨论】:

标签: jquery asp.net-mvc


【解决方案1】:

像这样:

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>");
            });
        });
    });
});

类似的...

【讨论】:

  • 我可以在 json 中发送选定的值吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 2020-01-12
相关资源
最近更新 更多