Asp.net mvc SelectList仅当System.Web.Mvc.SelectList的值有效时,如何设置所选项目
创建SelectList时,您可以选择传入SelectedValue属性,文档中会显示该属性Asp.net mvc SelectList仅当System.Web.Mvc.SelectList的值有效时,如何设置所选项目,asp.net-mvc,asp.net-mvc-5,selectlist,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
// 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);
}
}
使用System.Web.Mvc;
分类某个项目
{
公共int id{get;set;}
公共字符串文本{get;set;}
}
类CreateSelectList
{
公共静态SelectList CreateSelectList()
{
列表项=新列表();
对于(int i=0;i<3;i++)
{
Add(newsomeItem(){id=i,text=i.ToString()});
}
//5不在项目列表中,但属性SelectedValue不=5
返回新的选择列表(项目“id”、“文本”5);
}
}
我的问题是:
如果您的代码接近您的真实场景,那么您可以使用如下内容
// 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");
}
回答很好,但我的代码演示了这个问题,我的问题是真正的代码使用泛型,我不知道所选值的项是什么或对象类型,例如,我实际上不知道其名为“id”的方法这是CreateSelectList(List items,ITitle emptyItem,object selectedValue)@安德姆:那你为什么不选择这个泛型函数之外的元素呢?在泛型方法中可能有一些方法可以做到这一点,但我认为这会使它过于复杂。