SelectList如何仅在System.Web.Mvc.SelectList的有效值时设置所选项

时间:2014-08-12 12:32:35

标签: asp.net-mvc asp.net-mvc-5 selectlist

创建SelectList时,您可以选择传入文档所示的SelectedValue属性

// selectedValue:
// The selected value. Used to match the Selected property of the corresponding
// System.Web.Mvc.SelectListItem.

但是,如果传递一个未包含在项列表中的值对象,它仍会设置所选值。试试这个:

using System.Web.Mvc;

class SomeItem
{
    public int id { get; set; }
    public string text { get; set; }
}

class CreateSelectList
{
    public static SelectList CreateSelectList() 
    {
        List<SomeItem> items = new List<SomeItem>();
        for (int i = 0; i < 3; i++)
        {
            items.Add(new SomeItem() { id = i, text = i.ToString() });
        }

        // 5 is not in the list of items yet the property SelectedValue does = 5
        return new SelectList(items, "id", "text", 5); 
     }
}

我的问题是:

  1. 由于我只想在存在时懒得设置我选择的值,我只想传入一个值并在列表中不存在时忽略它,但是如何? (这是一个错误或设计特征),或

  2. 如果您创建一个SelectList 而不是 SelectedValue,在构建之后,如何设置SelectedValue(当它存在于列表中时)?

1 个答案:

答案 0 :(得分:1)

如果您的代码接近真实场景,则可以使用类似

的内容
// check if there is any element with id = 5 
if (items.Any(i => i.id == 5)) 
{
    // there is an element with id = 5 so I set the selected value
    return new SelectList(items, "id", "text", 5); 
}
else
{
    // there is no element with id = 5 so I don't set the selected value
    return new SelectList(items, "id", "text");
}