2009-04-14 51 views
2

在尝试更多级联下拉之后,我决定通过Jquery来完成。如何让Json对象下拉?

这是我cityController

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。但不工作。

+0

你也可以做到这一点而不必通过使用http://awesome.codeplex.com中的AjaxDropdown来了解/写入jQuery实时演示:http://demo.aspnetawesome.com/AjaxDropdownDemo – Omu 2012-02-22 19:14:05

回答

4

像这样:

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

OR,而不是使用页面加载,我会完全使用它的jQuery:

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

类似的东西...

+0

我可以在json中发送选定的值吗? – Vikas 2009-04-16 05:51:19