带有where子句的人口下拉列表

时间:2015-04-06 19:39:30

标签: asp.net-mvc

我想使用数据库中的值填充第二个下拉列表GetCity(),这些值取决于在第一个列表或GetCounty()下拉列表中选择的内容。我在哪里添加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>

1 个答案:

答案 0 :(得分: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;
        }