سلام دوستان
من از کد زیر برای نمایش گروه ها و زیر گروه ها در dropdownlist استفاده میکنم
دوست داشتم نظر شما رو بدونم و اگه از کد بهتری استفاده می کنید بفرمائید
ممنون
public ActionResult Index() {
DropdownModel objdropdownmodel = new DropdownModel();
objdropdownmodel.ParentDataModel = new List<Parent>();
objdropdownmodel.ParentDataModel = GetParentData();
objdropdownmodel.ClildDataModel = new List<Clild>();
objdropdownmodel.ClildDataModel = GetClildData();
return View(objdropdownmodel);
}
public IEnumerable<Parent> GetParentData() {
IEnumerable<Parent> objparent = db.Goroh.Where(g => g.ParentId == null).ToList().Select(s => new Parent
{
ParentId = s.Id,
ParentName = "--" + s.nam + "--"
});
return objparent;
}
public IEnumerable<Clild> GetClildData() {
IEnumerable<Clild> objchild = db.Goroh.Where(g => g.ParentId != null).ToList().Select(s => new Clild
{
ChildId = s.Id,
ChildName = s.nam,
ParentId = s.ParentId.Value
});
return objchild;
}
public class DropdownModel {
public List<Parent> DropdownDataModel { get; set; }
public IEnumerable<Parent> ParentDataModel { get; set; }
public IEnumerable<Clild> ClildDataModel { get; set; }
public Guid SelectedValue { get; set; }
}
public class Parent
{
public Guid ParentId { get; set; }
public string ParentName { get; set; }
}
public class Clild
{
public Guid? ParentId { get; set; }
public Guid ChildId { get; set; }
public string ChildName { get; set; }
}
<select name="TeavelMode" id="ddltravelmode"> <option value="0">Select</option>
@foreach (var pitem in Model.ParentDataModel)
{
<optgroup label="@pitem.ParentName">
@{
var childitemfilter = Model.ClildDataModel.Where(m => m.ParentId == pitem.ParentId);
if (childitemfilter != null)
{
foreach (var citem in childitemfilter)
{
string selectedValue = "";
if (Model.SelectedValue == citem.ChildId)
{
selectedValue = "selected='selected'";
}
<option value="@citem.ChildId" @selectedValue>@citem.ChildName</option>
}
}
}
</optgroup>
}
</select>