2009-10-21 97 views
1

加载dropdownlists我有一个看起来有点类似这个ASP.NET MVC - 基于选择的值

<% using (Html.BeginForm()) {%> 
    <%= Html.DropDownList("Category") %> 
    <%= Html.DropDownList("SubCategory") %> 
    <input type="submit" value="Print" /> 
    <%= Html.ActionLink("Cancel", "Index") %> 
<% } %> 

如果有人知道我怎么可以加载基于所选类别的子类别我想知道一个看法? 在webforms我只是使用autopostback事件来做到这一点,但我有点困惑如何使用mvc框架来做到这一点。

在此先感谢

回答

2

改变你的看法是这样的:

<% using (Html.BeginForm()) {%> 
    <%= Html.DropDownList("Category", Model.SelectList, new {onchange = "actualize(this);"}) %> 
    <div id="selectdiv"> 
    <% Html.RenderPartial("SubCategories"); %> 
    </div> 
    <input type="submit" value="Print" /> 
    <%= Html.ActionLink("Cancel", "Index") %> 
<% } %> 

<script type="text/javascript"> 

function actualize(obj) 
{ 
    $.ajax({ 
     url: url, 
     async: true, 
     type: 'POST', 
     data: { id: obj.value }, 
     dataType: 'text', 
     success: function(data) { $("#selectdiv").html(data); }, 
     error: function() { 
      console.log('Erreur'); 
     } 
    }); 
} 

</script> 

创建一个名为SubCategories.aspx控制,包括在它:

<%= Html.DropDownList("SubCategory",Model.SelectList) %> 

创建一个模型类

public class MyModel 
{ 
    public SelectList SelectList {get;set;} 
} 

创建一个控制器动作

public ActionResult SubCategories(int id) 
{ 
    MyModel model = new MyModel(); 
    model.SelectList = new SelectList(YourRepository.GetSubCategories(id),"Id","Name"); 
    return View(model); 
} 
+0

希望看到部分视图中的下拉列表,以便它可以重新使用。所以不要有两个下拉菜单,而只需要一个局部视图。使造型更容易一些,你只需要做一次。我知道这是有点多余的一个单一的下拉列表,但在我的经验,这然后成为第二性质与更大的可重用组件 – griegs 2009-10-21 03:52:59

+0

如果你读,第二个下拉是在一个名为SubCategories.aspx的局部视图:) – Gregoire 2009-10-21 11:45:48

+0

如果有另一个下降在依赖于类别和子类别的子类别之后,您是否会建议将它放在另一个部分视图中? – AlteredConcept 2009-11-10 18:59:24

1

放置一个PartialView内的下拉列表。然后,当你回发PartialView(“viewName”,model)。然后在你的jQuery的返回中,用返回的新html代替部分视图。

所以你是查看;

<div id="myPartialView"> 
    <% Html.PartialView("PartialViewName", model); %> 
</div> 

那么你的jQuery不会像

$('#myPartialView').html = retHtml; 

你的C#

return PartialView("PartialViewName", model); 

未经测试,但是这就是我想你想采取的方法。