2015-04-06 49 views
-1

我想用数据库中的值填充第二个下拉列表GetCity(),这些值取决于第一个列表或GetCounty()下拉列表中选择的内容。我在哪里添加where子句?人口与where条款的下拉列表

public class NewsModel : BaseModel 
{ 
    [Required] 
    public int? FKCountyId { get; set; } 
    public string County { get; set; } 
    [Required] 
    public int? FKCityId { get; set; } 
    public string City { get; set; } 


    public List<SelectListItem> GetCounty() 
    { 
     List<SelectListItem> lst = new List<SelectListItem>(); 
     lst.Add(new SelectListItem() { Text = "Please select County", Value = "" }); 
     foreach (var item in LambertonContext.NewsCounties) 
     { 
      lst.Add(new SelectListItem() { Text = item.County, Value = item.PKCountyId.ToString() }); 
     } 
     return lst; 
    } 

    public List<SelectListItem> GetCity() 
    { 
     List<SelectListItem> lst = new List<SelectListItem>(); 
     lst.Add(new SelectListItem() { Text = "Please select City", Value = "" }); 
     foreach (var item in LambertonContext.NewsCities) 
     { 
      lst.Add(new SelectListItem() { Text = item.City, Value = item.PKCityId.ToString() }); 
     } 
     return lst; 
     } 
} 


<div class="panel-body"> 
       <div class="form-group"> 
        @Html.LabelFor(m => m.FKCountyId, new { @class = "col-sm-2 col-sm-2 control-label" }) 
        <div class="col-sm-10"> 
         @Html.DropDownListFor(m => m.FKCountyId, Model.GetCounty()) 
        </div> 
       </div> 
       <div class="form-group"> 
        @Html.LabelFor(m => m.FKCityId, new { @class = "col-sm-2 col-sm-2 control-label" }) 
        <div class="col-sm-10"> 
         @Html.DropDownListFor(m => m.FKCityId, Model.GetCity()) 
        </div> 
       </div> 

回答

0

您需要将CountyId传递到您的GetCity()和过滤列表; 试试这个:

public List<SelectListItem> GetCity(string CountyId) 
    { 
     List<SelectListItem> lst = new List<SelectListItem>(); 
     lst.Add(new SelectListItem() { Text = "Please select City", Value = "" }); 
     foreach (var item in LambertonContext.NewsCities.Where(FKCountyId == GetCounty().Value)) 
     { 
      lst.Add(new SelectListItem() { Text = item.City, Value = item.PKCityId.ToString() }); 
     } 
     return lst; 
     } 
+0

阿兰多拉,我一定要回发GetCounty下拉菜单来获取在下拉列表中选择的价值? – user2224493

+1

你不需要回传,你已经有FK关系。 您将需要一个AJAX调用来填充城市下拉列表 –

+0

OK但LambertonContext.NewsCities.Where(FKCountyId == GetCounty()。Value)给我错误'System.Collections.Generic.List '不包含'Value'的定义,并且不能找到接受类型'System.Collections.Generic.List '的第一个参数的扩展方法'Value' (你是否缺少使用指令或程序集引用?) – user2224493