如何填写下拉和依赖下拉菜单

时间:2016-03-29 14:01:08

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

这是我的视图模型For Dropdown

    [Required(ErrorMessage = "Gerekli Alan")]
    [Display(Name = "İl")]
    [UIHint("DropDownList")]
    [AdditionalMetadata("DataController", "Register")]
    [AdditionalMetadata("DataAction", "Province")]
    public int? ProvinceId { get; set; }

    [Required(ErrorMessage = "Gerekli Alan")]
    [Display(Name = "İlçe")]
    [UIHint("DependentDropDownList")]
    [AdditionalMetadata("DependsOn", "ProvinceId")]
    [AdditionalMetadata("DataController", "Register")]
    [AdditionalMetadata("DataAction", "TownByProvinceId")]
    public int? TownId { get; set; }

这是控制器

[HttpPost]
    public ActionResult Province()
    {

        IQueryable<DropDownListItem> queryable = from city in Db.Provinces
                                                 orderby city.Name
                                                 select new DropDownListItem { Text = city.Name, Value = city.Id };
        return base.Json(queryable);
    }

    [HttpPost]
    public ActionResult TownByProvinceId(int ProvinceId)
    {
        IQueryable<DropDownListItem> queryable = from province in Db.Towns
                                                 where province.ProvinceId == ProvinceId
                                                 orderby province.Name
                                                 select new DropDownListItem { Text = province.Name, Value = province.Id };
        return base.Json(queryable);
    }

我正在尝试按省选择的城镇列出ITem如何在视图中填写下拉列表?

1 个答案:

答案 0 :(得分:0)

SelectListItem可能会有更好的运气。

在ViewModel中创建类型为List<SelectListItem>

的属性

在调用视图之前,请填充属性。

var model = new MyViewModel { queryable = from province in Db.Towns
                                         where province.ProvinceId == ProvinceId
                                         orderby province.Name
                                         select new SelectListItem { Text = province.Name, Value = province.Id, Selected = false }};

然后在你的观点中你就这样称呼它。

@Html.DropDownListFor(m => m.ProvinceId, m.queryable)

这会为您提供一个下拉菜单,其中包含queryableProvinceId上存储在回发中的所有值。