根据另一个分配选择列表

时间:2016-08-10 13:09:41

标签: jquery asp.net-mvc

我的视图模型如下所示:

public IList<TeamCategory> TeamCategories { get; set; } 
public IEnumerable<SelectListItem> TeamCategoriesList { get; set; }
 public IList<CategoryInput> CategoryInputs { get; set; }

public class CategoryInput
{
    public string CategoryName { get; set; }
    public IEnumerable<SelectListItem> VenueList { get; set; }
}

查询:

foreach (var teamCategory in model.TeamCategories)
            {
                var categoryInput = new CategoryInput()
                {
                    CategoryName = teamCategory.Name,
                    VenueList = teamCategory.Venues.Select(x => new SelectListItem()
                    {
                        Value = x.Id,
                        Text = x.Address
                    }),
                };

                model.CategoryInputs.Add(categoryInput);
            }

查看:

@Html.DropDownList("TeamCategory", Model.TeamCategoriesList, new {@id = "categorieslist"})

@Html.DropDownList("Venue", new List<SelectListItem>(), new {@id = "venuelist" })

所以它首先填充了teamcategories列表和一个空的场地列表,然后当我更改类别时,我希望场地列表更新到与该类别相关的列表,从查询中可以看出

我已经开始了事件监听器,但在那之后我不知所措:

$('#categorieslist').change(function() {
            AssignVenues();
        });

function AssignVenues() {
                var category = $('#categorieslist').val();

            }

1 个答案:

答案 0 :(得分:1)

您需要收听TeamCategory选择元素上的change事件,获取所选的选项值并对您的服务器进行ajax调用,您将收到所选的团队类别ID,获取该类别ID的地点并以JSON格式返回结果。

@section Scripts
{
 <script>
   $(function(){

     $("#categorieslist").change(function(){

         var teamCategoryId=$(this).val();
         $("#venuelist").html("");
         var venues="";

         $.getJSON('@Url.Action("GetVenues","Home")/'+teamCategoryId,function(data){
           $.each(data,function(a,b){
              venues+="<option value='"+b.Value+"'>"+b.Text+"</option>";
           });
           $("#venuelist").html(venues);
         });

     });

  });
</script>
}

假设您的GetVenues中有一个HomeController方法,该方法会返回一个SelectListItem的列表

public ActionResult GetVenues(int id)
{
   var list=new List<SelectListItem>();
   // I am hard coding 2 venues. 
   // You may replace it with your real data for the id passed in.

   list.Add(new SelectListItem { Value="1", Text="Ann Arbor"});
   list.Add(new SelectListItem { Value="2", Text="Detroit"});

   return Json(list,JsonRequestBehaviour.AllowGet);
}