C# SelectList selectedValue不工作

C# SelectList selectedValue不工作,c#,.net,model-view-controller,enums,extension-methods,C#,.net,Model View Controller,Enums,Extension Methods,我编写了一个扩展方法来读取视图中的枚举数值,并返回一个Select的HTML,其中包含所有枚举数值,并且选择了加载的控制器 我把它称为: @Html.DropDownListFor(m => m.ItemType, Model.ItemTypeList) 在我的模型中: public IEnumerable<SelectListItem> ItemTypeList { get; set; } 另外,我的后端扩展方法是: public static IEnumerable&l

我编写了一个扩展方法来读取视图中的枚举数值,并返回一个Select的HTML,其中包含所有枚举数值,并且选择了加载的控制器

我把它称为:

@Html.DropDownListFor(m => m.ItemType, Model.ItemTypeList)
在我的模型中:

public IEnumerable<SelectListItem> ItemTypeList { get; set; }
另外,我的后端扩展方法是:

public static IEnumerable<SelectListItem> ToLocalizatedSelectList(this Type enumType)
    {
        return (from object item in Enum.GetValues(enumType)
                let title = item.GetDescription()
                let value = ((int)item).ToString(CultureInfo.InvariantCulture)
                select new SelectListItem
                {
                    Value = value,
                    Text = title
                }).ToList();
    }
我将返回列表中的所有枚举值,并使用此代码将它们显示在select中。我能够在数据库中恢复所选的值。但问题是,即使方法
toLocalizedSelectList
返回ienumerable列表中的选定项,当页面加载时,它也不会显示选定的值,始终显示第一个值

我需要做点什么,在它工作之后,还是我的错误是关于别的

---------编辑-----------

我是如何解决问题的:

我使用enumName作为值,更改了ToLocalizedSelectList(此类型为enumType)中enum itens的值。当我把它转换成int时,代码保存了数据库中的值,但是代码不认为它是一个选定的值。 纠正方法:

public static IEnumerable<SelectListItem> ToLocalizatedSelectList(this Type enumType)
    {
        return (from object item in Enum.GetValues(enumType)
                let title = item.GetDescription()
                let value = item.ToString()
                select new SelectListItem
                {
                    Value = value,
                    Text = title
                }).ToList();
    }
公共静态IEnumerable ToLocalizedSelectList(此类型为enumType)
{
返回(来自Enum.GetValues(enumType)中的对象项)
让title=item.GetDescription()
let value=item.ToString()
选择新的SelectListItem
{
值=值,
文本=标题
}).ToList();
}

这里有很多奇怪和不必要的代码。至少使用
返回htmlhelp.DropDownListFor(表达式,…)
和从第一个创建第二个
IEnumerable
只是毫无意义的额外开销。但是,当您绑定到模型属性时,设置
SelectListItem
selectedValue
属性(并通过在
SelectList
构造函数中设置
selectedValue
值再次重复)是毫无意义的方法构建一个新的
IEnumerable
,并根据绑定到的属性值设置
选定的
属性。谢谢,@StephenMuecke。我更改了代码,经过一些尝试,我发现了错误并修复了它。此外,我还编辑了一个问题案例,有人想看看解决方案是否存在相同的问题。很抱歉我的垃圾代码,这种代码对我来说太高级了,我试图做一些可重用的事情。
public enum ItemTypeToSell
{
    [LocalizedDescription("Product", typeof(Expressions))]
    Product = 1,

    [LocalizedDescription("Addon", typeof(Expressions))]
    Addon = 2,

    [LocalizedDescription("Other", typeof(Expressions))]
    Other = 3
}
public static IEnumerable<SelectListItem> ToLocalizatedSelectList(this Type enumType)
    {
        return (from object item in Enum.GetValues(enumType)
                let title = item.GetDescription()
                let value = item.ToString()
                select new SelectListItem
                {
                    Value = value,
                    Text = title
                }).ToList();
    }