Ho根据用户从下拉列表中的选择显示多个复选框选项?

时间:2012-03-15 20:37:36

标签: jquery asp.net-mvc asp.net-mvc-3 c#-4.0 razor

我想在我的MVC3剃须刀应用程序上显示一个下拉框,用户可以从中选择类别,根据他的选择,我想显示子类别,这是复选框,因此用户可以选择多个子类别。

任何人都可以帮我解决这个问题吗?

下面是我从网络服务收到的json,并且我将其反序列化为对象,那么如何将该对象分配给两个不同的列表类别(下拉列表)和子类别(复选框)?

JSON:

 {
 "Code":0,
 "Status":"Done",
 "Categories":[
 {
  "ID":1,
  "Name":"Eat",
    "Subcategories":[
        {"Flag":false,"ID":100,"Name":"Food"},
        {"Flag":false,"ID":101,"Name":"Fast Food"},         
        {"Flag":false,"ID":102,"Name":"Other"}
    ]
        },
    {
    "ID":2,
    "Name":"Entertainment",
     "Subcategories":[
        {"Flag":false,"ID":100,"Name":"All"},               
        {"Flag":false,"ID":101,"Name":"Movie"},
        {"Flag":false,"ID":102,"Name":"Other"}
    ]
  },
  }
  ]
  }

实体:

public class MyData
{
  public int Code { get; set; }
  public string Status { get; set; }
  public List<Category> Categories { get; set; }
}

public class Category
{
  public string Name { get; set; }
  public int ID { get; set; }
  public List<Subcategory> Subcategories { get; set; }
}

public class Subcategory
{
  public string Name { get; set; }
  public int ID { get; set; }
  public bool Flag { get; set; }
}

1 个答案:

答案 0 :(得分:1)

你可以使用AJAX。订阅下拉列表的更改事件,并向传递给所​​选类别的控制器操作触发AJAX请求。该操作将在数据库中查询相应的子类别,并返回带有相应复选框的部分视图,这些复选框将注入到DOM中。

因此,假设您已经有了视图中类别的下拉列表:

@Html.DropDownListFor(
    x => x.CategoryId, 
    Model.Categories, 
    new { 
        id = "categories",
        data_subcategoriesurl = Url.Action("subcategories", "somecontroller")
    }
)

和一些div,它将在页面的某处包含子类别:

<div id="subcategories">
    @Html.EditorFor(x => x.SubCategories, "SubCategories")
</div>

然后您可以使用SubCategories.cshtml部分来呈现复选框列表:

@model IList<CategoryViewModel>
@{
    // we change the HTML field prefix so that input elements
    // such as checkboxes have correct names in order to be able
    // to POST the values back 
    ViewData.TemplateInfo.HtmlFieldPrefix = "SubCategories";
}
@for (var i = 0; i < Model.Count; i++)
{
    <div>
        @Html.LabelFor(x => x[i].IsSelected, Model.CategoryName)
        @Html.CheckBoxFor(x => x[i].IsSelected)
    </div>
}

现在,您可以在单独的javascript文件中订阅下拉列表的更改事件:

$(function() {
    $('#categories').change(function() {
        var subcategoriesUrl = $(this).data('subcategoriesurl');
        var selectedCategoryId = $(this).val();
        $('#subcategories').load(subcategoriesUrl, { id: selectedCategoryId });
    });
});

最后是用AJAX调用的SubCategories动作:

public ActionResult SubCategories(int? id)
{
    var subCategories = Repository.GetSubCategories(id);
    return View(subCategories);
}