2009-09-30 29 views
0

我试图从另一个下拉列表中选择项目时创建下拉列表。我使用$ .getJSON从控制器中的操作获取数据,这里是我的代码。 jQuery代码看起来是这样的。

 $(function() { 
     $("#GroupName").change(function() { 
      //alert("Test"); 
      var str = ""; 
      $("select option:selected").each(function() { 
       str = $(this).val(); 
      }); 
      var url = '<%= Url.Action("GetMetrics", "Groups") %>'; 
      $.getJSON(url, { id : str }, function(data) { $("#metrics").fillSelect(data); }); 
     }) 
     //  .change(); 

    }); 

我的观点看起来像这样。

<p><label for="GroupId">Group</label><br /> 
    <%= Html.DropDownList("GroupName", "")%>  
<span></span> 
</p> 

<p><label for="GroupId">Group</label><br /> 
    <select id="metrics" > 
</select> 
<span></span> 
</p> 

和我的操作:

public ActionResult GetMetrics(string id) 
{ 
    int cId = Convert.ToInt16(id); 
    //var group = Group.GetGroupByID(cId); 
    List<Metric> metrics = Metric.GetMetrics(cId); 

    return Json(metrics); 
} 

这里是我的路由:

routes.MapRoute(
     "Default",            // Route name 
     "{controller}/{action}/{id}",       // URL with parameters 
     new { controller = "Home", action = "Index", id = "" } // Parameter defaults 
    ); 

问题是我无法从Jquery的传递参数和我的目标不添加列表项下拉列表是指标。请帮忙!

回答

0

我不知道这是否会回答你的问题,我没有时间深入进去所以这里是一些代码,我这回发使用jQuery的时候选择列表的变化并带回另一个选择列表中写道。

很简单的例子。道歉,如果这不是你问的。

jQuery代码在图;

<script> 

    $(document).ready(function() { 
     $("#selSegment").change(function() { 
      if ($("#selSegment").val() != "") { 
       $.post("/Home/jQueryGetCoverTypes", { segment: $("#selSegment").val() }, function(retHTML) { 
        document.getElementById("coverSelector").innerHTML = retHTML; 
       }); 
      } 
      else { 
       document.getElementById("coverSelector").innerHTML = ""; 
      } 
     }); 
    }); 
</script> 

与第二选择相关联的列表中选择DIV控制;

 <tr> 
      <td> 
       <select id="selSegment"> 
        <option value="">Please select</option> 
        <option value="combination">Combination Hospital and Extras Cover</option> 
        <option value="hospital">Hospital Cover</option> 
        <option value="extras">Extras Cover</option> 
        <option value="mix">Mix and Match Hospitals and Extras Cover</option> 
       </select> 
      </td> 
     </tr> 
     <tr> 
      <td id="coverSelector"> 

      </td> 

我的控制器的代码;

public ActionResult jQueryGetCoverTypes(string segment) { List items = new List();

for(int t = 0; t <= 4; t++) 
     items.Add(segment + " " + t.ToString()); 

    if (string.IsNullOrEmpty(segment)) 
     return PartialView("CoverSelector", new List<string>{ "Please select a cover type" }); 

    return PartialView("CoverSelector", items); 
} 

希望这可以帮助你。

1

你有没有尝试过这样的:

var url = '<%= Url.Action("GetMetrics", "Groups") %>' + '/' + str;   
$.getJSON(url, function(data) { $("#metrics").fillSelect(data); }); 

我用同样的方法,它是工作。