本文介绍了MVC-设置SelectList的选定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在没有选择值的情况下实例化SelectList后,如何设置它的selectedvalue属性;

How can I set the selectedvalue property of a SelectList after it was instantiated without a selectedvalue;

SelectList selectList = new SelectList(items, "ID", "Name");

在此阶段之后,我需要设置选定的值

I need to set the selected value after this stage

推荐答案

如果您有SelectList对象,只需遍历其中的各项并设置所需项的"Selected"属性.

If you have your SelectList object, just iterate through the items in it and set the "Selected" property of the item you wish.

foreach (var item in selectList.Items)
{
  if (item.Value == selectedValue)
  {
    item.Selected = true;
    break;
  }
}

或使用Linq:

var selected = list.Where(x => x.Value == "selectedValue").First();
selected.Selected = true;

这篇关于MVC-设置SelectList的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 23:27