0

我有一个Region类是这样的:如何在dropdownlistfor上禁用父项?

public class Region 
{ 
    public int Id { get; set; } 
    public int Name { get; set; } 

    public int ParentId { get; set; } 
} 

而且Person具有区域:

public class Person 
{ 
    public int Id { get; set; } 
    public int Name { get; set; } 
    public int SurName { get; set; } 

    public int RegionId { get; set; } 
} 

但是,它不像树节点。只有2层。国家及其子区域 - 城市。我使用引导模板。

我收集这个地区这样的名单:

Country1 //need to disable this 
    City1 
    City2 
    City3 
Country2 //need to disable this 
    City1 
    City2 

亲自创建行动:

Viewbag.Regions = new SelectList(MyRepository.LoadRegions(), "Id", "Name"); 

,并考虑:

@Html.DropDownListFor(model => model.RegionId, ViewBag.Regions as IEnumerable<SelectListItem>, "-", new { data_rel = "chosen", @id = "region" }) 

最后,我下拉打开时需要,要禁用国家,只能选择城市。

如何禁用dropdownlis中的元素parentId == 0

+0

[创建一个SelectListItem与disabled =“disabled”属性]的可能的重复(http://stackoverflow.com/questions/2655035/creating-a-selectlistitem-with-the-disabled-disabled-attribute) –

回答

0

您可以采取的一种方法是加载区域,删除父项目,然后将SelectList分配给Viewbag。

var regions = MyRepository.LoadRegions(); 
/* remove parent items from regions */ 
ViewBag.Regions = new SelectList(regions, "Id", "Name"); 

编辑我以前误解的问题。你想拥有不可选的标题。我发现this question关于MVC支持OptGroups(我认为这将完成你要去的)。原来的基础Html.DropDown帮手不支持它,但你可以写一个自定义的,并在链接的问题有一个自定义助手样本的情况下。

+1

但是我想要显示,但要禁用它们 –

+0

啊!我想我更了解你的问题,我编辑了一个潜在的解决方案。 –

+1

谢谢,我已经完成了我的问题。我也使用了htmlhelpers。对于这个想法,我接受你的答案。 –