Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc SelectList仅当System.Web.Mvc.SelectList的值有效时,如何设置所选项目_Asp.net Mvc_Asp.net Mvc 5_Selectlist - Fatal编程技术网

Asp.net mvc SelectList仅当System.Web.Mvc.SelectList的值有效时,如何设置所选项目

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

创建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); 
     }
}
使用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);
}
}
我的问题是:

  • 由于我只想在所选值存在时才惰性地设置它,所以我只想传入一个值,当它不在列表中时将其忽略,但是如何设置呢?(这是一个bug还是一个设计特性),或者

  • 如果您创建了一个SelectList,但没有创建SelectedValue,那么在构建它之后,如何设置SelectedValue(当它存在于列表中时再次设置)


  • 如果您的代码接近您的真实场景,那么您可以使用如下内容

    // 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)@安德姆:那你为什么不选择这个泛型函数之外的元素呢?在泛型方法中可能有一些方法可以做到这一点,但我认为这会使它过于复杂。