Hi @Andrus
How to order and group by select elemnt option list by 3 properties: countryCode, city ,companyName Should domTree sorted and grouped?
Yes, to group related options in a drop-down list, it is better to sort and group the domTree.
Try to create the following view model, use them to store the grouped and sorted result.
public class CountryDataViewModel
{
public string CountryCode { get; set; }
public List<CityDataViewModel> Data { get; set; }
}
public class CityDataViewModel
{
public string City { get; set; }
public JsonNode[] SubData { get; set; }
}
Then, in the controller, use the following code to sort and group the json data:
public async Task<IActionResult> Index()
{
using HttpClient client = new() { BaseAddress = new Uri("http://ftp.dpdbaltics.com") };
var domTree = await client.GetFromJsonAsync<JsonNode>("PickupParcelShopData.json");
var result = domTree.AsArray().GroupBy(c => (string)c["countryCode"]).Select(c=>
new CountryDataViewModel()
{
CountryCode = c.Key,
Data = c.GroupBy(d => (string)d["city"]).Select( e=>
new CityDataViewModel()
{
City = e.Key,
SubData = e.OrderBy(d => (string)d["companyName"]).ToArray()
}
).ToList()
}).ToList();
ViewBag.domtree = result;
return View();
}
In the view page, use optgroup
element to add groups in the drop-down list.
@{
var domTree = ViewBag.domtree as List<CountryDataViewModel>;
}
<select id='dpd_select'>
@foreach (var country in domTree)
{
<optgroup label="@country.CountryCode">
@foreach (var city in country.Data)
{
<optgroup label=" @city.City">
@foreach (var esi in city.SubData)
{
<option value='@esi["parcelShopId"]'>@esi["companyName"]</option>
}
</optgroup>
}
</optgroup>
}
</select>
The result as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion