2013-08-27 54 views
0
var userColor = db.userColor; 
foreach(var x in userColor){ 
    var correspondingDropDownValue = from m in db.user 
            where m.UserID == x.UserID 
            select m; 

ViewData["dropDown_Color"] = correspondingDropDownValue.Select(j => new SelectListItem { Text = j.ListOfValue, Value = j.ListOfValue }).ToList(); 
} 

在此db.userColor表中有另一個名爲db.userColor.default的列,其中包含一個用作默認值的值。我如何修改上面的代碼來設置選定的值?MVC DropDownList設置默認值

回答

1

使用的SelectListItemSelected屬性,以確定哪些應該被默認選擇:

ViewData["dropDown_Color"] = correspondingDropDownValue.Select(j => new SelectListItem { Text = j.ListOfValue, Value = j.ListOfValue, Selected = j.ListOfValue == j.userColor.default }).ToList(); 

不能夠看到您的模式,我猜其中userColor.default是的,但你可以根據需要更新邏輯。

0
Use the below code to set property 

List<LimitType> objLimitTypeList = new List<LimitType>(); 

     LimitType objLimitType = new LimitType(); 
     objLimitType.WithinLimitCode = 0; 
     objLimitType.WithinLimitName = "Within Limit"; 
     objLimitTypeList.Add(objLimitType); 

     LimitType objLimitTypeN = new LimitType(); 
     objLimitTypeN.WithinLimitCode = 1; 
     objLimitTypeN.WithinLimitName = "Over Limit"; 
     objLimitTypeList.Add(objLimitTypeN); 

     if (BtnAct.ToLower() == "add") 
     { 
      ViewBag.WithinLimit = new SelectList(objLimitTypeList, "WithinLimitCode", "WithinLimitName"); 
     } 
     else 
     { 
      if (IsWithinLimit.ToLower() == "y") 
       ViewBag.WithinLimit = new SelectList(objLimitTypeList, "WithinLimitCode", "WithinLimitName", 0); 
      else 
       ViewBag.WithinLimit = new SelectList(objLimitTypeList, "WithinLimitCode", "WithinLimitName", 1); 

     }