0

How to set selected true from contains list string in linq ???

I want to set selected true if some field is same from variabel list string. this is my code for my case.

string detail = Request.QueryString["detail"];            
List<string> KdUser = new List<string>();            
if (detail != null) {
   KdUser = (from u in db.TUserSelecteds where u.detail_guid_edis == new  Guid(detail) select u.kode_user).ToList(); 
}
// KdUser = [0]U002,[1]U001,[2]U003

 List<SelectListItem> items = (from us in db.Users
                                         where us.ApplicationId == "TMS-APP-03" && us.IsActive == 1
                                         orderby us.NamaKaryawan
                                         select new SelectListItem()
                                         {
                                             Text = us.NamaKaryawan,
                                             Value = us.KodeUser
                                             //Selected = true => If (Value Contains KdUser)
                                         }).ToList();

I hope you understand what i mean. thanks

achmad darmawan
  • 125
  • 1
  • 1
  • 9
  • Use ternary operator: `Selected = (us.KodeUser.Contains(KdUser)) ? true : false` – Tetsuya Yamamoto Nov 27 '17 at 03:35
  • 1
    What would be the point. The `Selected` property is ignored when your bind to your model property (its the value of the property that determines what is selected) –  Nov 27 '17 at 03:36
  • Suggest you read [this answer](https://stackoverflow.com/questions/41719293/mvc5-how-to-set-selectedvalue-in-dropdownlistfor-html-helper/41731685#41731685) –  Nov 27 '17 at 03:44

1 Answers1

0
List<SelectListItem> items = (from us in db.Users
                              where us.ApplicationId == "TMS-APP-03" && us.IsActive == 1
                              orderby us.NamaKaryawan
                              select new SelectListItem()
                              {
                                  Text = us.NamaKaryawan,
                                  Value = us.KodeUser
                                  Selected = KdUser.Contains(us.KodeUser)
                              }).ToList();
Backs
  • 24,430
  • 5
  • 58
  • 85
  • @achmaddarmawan. If you think that worked it can only mean your view is wrong and/or you not binding to a model. –  Nov 27 '17 at 04:07