ASP.NET MVC - 根据选定的值加载下拉列表

时间:2009-10-21 03:32:10

标签: asp.net-mvc drop-down-menu

我有一个看起来有点类似于

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

我想知道是否有人知道如何根据所选类别加载子类别? 在webforms中,我只是使用autopostback事件来做这件事,但我对使用mvc框架如何做到这一点感到困惑。

提前致谢

2 个答案:

答案 0 :(得分: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) %>

创建一个Model类

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

答案 1 :(得分:1)

将下拉列表放在PartialView中。然后当你发回来做一个返回PartialView(“viewName”,模型)。然后在返回jQuery时,只需用返回的新html替换部分视图。

所以你在看;

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

然后你的jQuery做了像

这样的事情
$('#myPartialView').html = retHtml;

你的C#

return PartialView("PartialViewName", model);

未经测试,但这是我认为您想采取的方法。