MVC DropDownList设置默认值

时间:2013-08-27 11:24:42

标签: asp.net-mvc drop-down-menu html-select

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的列,它带有一个用作默认值的值。如何修改上面的代码来设置所选的值?

2 个答案:

答案 0 :(得分:1)

使用Selected的{​​{1}}属性来确定默认情况下应选择哪个属性:

SelectListItem

无法看到您的架构,我猜测ViewData["dropDown_Color"] = correspondingDropDownValue.Select(j => new SelectListItem { Text = j.ListOfValue, Value = j.ListOfValue, Selected = j.ListOfValue == j.userColor.default }).ToList(); 在哪里,但您可以根据需要更新逻辑。

答案 1 :(得分: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);

        }