1

MVC HtmlHelper.DropDownFor 方法使用起来可能非常令人沮丧。通常情况下,您的选择不会保留,或者您的控件未正确绑定。您将如何编写自定义 HTML 帮助程序来填充枚举中的下拉列表?

4

1 回答 1

1

我花了最后几个小时试图弄清楚这一点,所以不妨分享我的发现。在尝试了各种排列,创建了一个测试应用程序来尝试各种选项并搜索了许多文章之后,我得到了一些适合我的东西。

第一点要提。SelectList 类有四个参数(最后三个是可选的)。如果您未指定选定值(最后一个参数),它将清除您在 SelectListItem 对象中设置的任何选定值(假设您创建了这些值的列表)。这让我沮丧了一段时间,因为我将其中一项 Selected 属性设置为 true,但是一旦我创建了 SelectList 对象,它总是设置为 false。

这是 SelectList 的 MVC 源代码供参考:

public class SelectList : MultiSelectList
{
    public SelectList(IEnumerable items)
        : this(items, null /* selectedValue */)
    {
    }

    public SelectList(IEnumerable items, object selectedValue)
        : this(items, null /* dataValuefield */, null /* dataTextField */, selectedValue)
    {
    }

    public SelectList(IEnumerable items, string dataValueField, string dataTextField)
        : this(items, dataValueField, dataTextField, null /* selectedValue */)
    {
    }

    public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue)
        : base(items, dataValueField, dataTextField, ToEnumerable(selectedValue))
    {
        SelectedValue = selectedValue;
    }

    public object SelectedValue { get; private set; }

    private static IEnumerable ToEnumerable(object selectedValue)
    {
        return (selectedValue != null) ? new object[] { selectedValue } : null;
    }
}

一旦我通过了那个小点,我就让我的助手从列表中正确选择项目并将值正确绑定回来。所以这是我创建的辅助方法(最初的方法来自另一篇文章,但这对我来说也不能正常工作):

public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null) where TProperty : struct, IConvertible
{
    if (!typeof(TProperty).IsEnum)
        throw new ArgumentException("TProperty must be an enumerated type");

    var selectedValue = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model.ToString();
    var selectList = new SelectList(from value in EnumHelper.GetValues<TProperty>()
                                    select new SelectListItem
                                                {
                                                    Text = value.ToDescriptionString(),
                                                    Value = value.ToString()
                                                }, "Value", "Text", selectedValue);

    return htmlHelper.DropDownListFor(expression, selectList, htmlAttributes);
}

(EnumHelper.GetValues 和 ToDescriptionString 是我的帮助方法,用于返回指定类型的枚举值列表并获取枚举描述的 EnumMember 值属性)如果有人需要,我可以发布该代码。

上面代码中的技巧是告诉 SelectList 值和文本属性是什么以及选定的值。

于 2013-01-21T15:10:01.983 回答