Current project:
I am trying to create a selection menu from OptGroupsfrom Models, but my problem is that I cannot build it myself OptGroups.
My model:
[DisplayName("City")]
public string CityId { get; set; }
private IList<SelectListItem> _CityName;
public IList<SelectListItem> CityName {
get {
List<SelectListItem> list = new List<SelectListItem>();
Dictionary<Guid, SelectListGroup> groups = new Dictionary<Guid, SelectListGroup>();
List<Region> region = db.Region.Where(x => x.Active == true).OrderBy(x => x.RegionName).ToList();
foreach(Region item in region) {
groups.Add(item.RegionId, new SelectListGroup() { Name = item.RegionName });
}
List<City> city = db.City.Where(x => x.Active == true).ToList();
foreach(City item in city) {
list.Add(new SelectListItem() { Text = item.CityName, Value = item.CityId.ToString(), Group = groups[item.RegionId] });
}
return list;
}
set { _CityName = value; }
}
Each city can be in a region. I want to select a menu for grouping cities by region. For all that I can figure out, the code above should do the job, but instead I get a drop-down menu with all the cities grouped in an OptGroup with the nameSystem.Web.Mvc.SelectListGroup
The key in the above code is that I first iterate over the regions and put them into the dictionary, and it is RegionIdset as the key that returns RegionName(which itself is formatted as SelectListGroup).
, RegionId.
, . 100% SelectListGroup SelectListItem.
, AFAIK:
@Html.DropDownListFor(x => x.CityId, new SelectList(Model.CityName, "Value", "Text", "Group", 1), "« ‹ Select › »", htmlAttributes: new { @class = "form-control" })
, , SelectList, DropDownList OptGroups, .
:
« ‹ Select › »
System.Web.Mvc.SelectListGroup
City1
City2
...
LastCity
:
« ‹ Select › »
Region1
City2
City4
City5
Region2
City3
City1
City6
?
: , , .
MVC , , , , -. , . .
"" , , , , . , [HttpGet], [HttpPost], , . , ( ViewBags) , , . . , .
, . , . - . - , , , . , , . , .
, - [HttpGet] [HttpPost] . , , . , Create Edit, ( , )
, , :
public class SelectLists {
public static IEnumerable<SelectListItem> CityNameList() {
ApplicationDbContext db = new ApplicationDbContext();
List<City> items = db.City.Where(x => x.Active == true).OrderBy(x => x.Region.RegionName).ThenBy(x => x.CityName).ToList();
return new SelectList(items, "CityId", "CityName", "Region.RegionName", 1);
}
}
, , . .
:
public string CityId { get; set; }
private IEnumerable<SelectListItem> _CityName;
public IEnumerable<SelectListItem> CityName {
get { return SelectLists.CityNameList(); }
set { _CityName = value; }
}
. , CityId Guid, - uniqueidentifier, , . , Value Guid. Guid, - . , CityName City - , CreateClientViewModel . , DropDownListFor, CityId , ( - ).
- get {}. , , , SelectLists, , CityNameList(). , , . , , (Create), , OptGroups, (Edit), .
, :
@Html.DropDownListFor(x => x.CityId, Model.CityName, "« ‹ Select › »", htmlAttributes: new { @class = "form-control" })
, , Model.ElementName.
, .