【问题标题】:Selected Property of SelectListItem and selectedValue parameter of SelectItem not workingSelectListItem 的 Selected 属性和 SelectItem 的 selectedValue 参数不起作用
【发布时间】:2012-09-18 21:25:19
【问题描述】:

我正在尝试开发一个 HtmlHelper 扩展方法:EnumDropDownListFor。无论我做什么,我都无法显示所选值。我尝试设置 SelectListItem 的 Selected=true 属性并设置 SelectList 构造函数的 selectedValue 。在调试时(在返回行),对于这两种情况,我都可以看到应该选择的 SelectLİstItem 的 Selected=true。但是当我“查看源代码”时,所有选项都没有 selected="selected" 属性。

我哪里错了?

注意:Toolkit 是我的实用程序类,ToByte 是 Enum 的扩展方法

    public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(
        this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string optionLabel = null,
        object htmlAttributes = null) where TModel : class
    {
        var selectedValue = helper.ViewData.Model == null
                                ? default(TProperty)
                                : expression.Compile()(helper.ViewData.Model);

        var enumVals = Toolkit.GetEnumValues(typeof(TProperty));

        //var selectList = from enumVal in enumVals.OfType<Enum>()
        //                 select new SelectListItem
        //                 {
        //                     Text = enumVal.GetName(),
        //                     Value = enumVal.ToByte().ToString(),
        //                     Selected = Equals(enumVal, Toolkit.To<Enum>(selectedValue))
        //                 };


        // helper.ViewData[(expression.Body as MemberExpression).Member.Name] = Toolkit.To<Enum>(selectedValue).ToByte().ToString();

        var selectList = new SelectList(from enumVal in enumVals.OfType<Enum>()
                                        select new
                                        {
                                            TextField = enumVal.GetName(),
                                            ValueField = enumVal.ToByte().ToString()
                                        }, "ValueField", "TextField", Toolkit.To<Enum>(selectedValue).ToByte().ToString());

        return helper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes);
    }

【问题讨论】:

    标签: asp.net-mvc enums html-helper selectlist


    【解决方案1】:

    我解决了(: 那是因为我用返回枚举类型的相同表达式调用“helper.DropDownListFor”,并且我试图通过“字节”转换值设置选项值。所以看起来 Expression 的返回值会覆盖给定的选定值,这很有意义。

    【讨论】:

    • 您能说明一下您是如何解决这个问题的吗?我目前面临同样的问题。你如何绕过它?
    猜你喜欢
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    相关资源
    最近更新 更多