0

I have a Region class like this:

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

   public int ParentId { get; set; }
}

And Person has region:

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

   public int RegionId { get; set; }
}

But, it is not like tree node. There are only 2 floors. Countries and it's sub regions - cities. I use bootstrap template.

I collect this regions like this list:

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

In person create action:

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

And in view:

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

Finally, I need when dropdown opens, to disable countries, it is possible to select only cities.

How can I disable elements in dropdownlis which parentId == 0 ?

Jeyhun Rahimov
  • 3,769
  • 6
  • 47
  • 90
  • possible duplicate of [Creating a SelectListItem with the disabled="disabled" attribute](http://stackoverflow.com/questions/2655035/creating-a-selectlistitem-with-the-disabled-disabled-attribute) – Jason P Aug 21 '13 at 13:40

1 Answers1

0

One approach you could take is to load up the Regions, remove the Parent items, and then assign the SelectList to the Viewbag.

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

EDIT I previously misunderstood the question. You want to have headers that aren't selectable. I found this question about MVC supporting OptGroups (which I think will accomplish what you're going for). Turns out the base Html.DropDown helper doesn't support it but you can write a custom one, and in the linked question there is a sample of a custom helper for this case.

Community
  • 1
  • 1
Dan Schnau
  • 1,505
  • 14
  • 17