10

这是相关的代码。请注意,我是在 Notepad++ 中完成的,而不是在工作中为我的项目复制代码。如果我在其中拼错了一个类名,假设它在我的代码中没有拼错。没有编译错误。

模型:

public class MyViewModel
{
    public int SelectedSomething { get; set; }

    public IList<int> Somethings { get; set; }
}

控制器:

public class MyController
{
    public ActionResult Index()
    {
        var viewModel = new MyViewModel();
        viewModel.Somethings = Enumerable.Range(1, 12).ToList();
        return View(viewModel);
    }
}

查看(剃刀):

@Html.DropDownListFor(x => x.SelectedSomething, new SelectList(Model.Somethings, Model.SelectedSomething), "Select an Option")

这将“起作用”,但不会在以下任何渲染option元素上设置值select

<select>
    <option value="">Select an Option</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
    <option>11</option>
    <option>12</option>
</select>

知道SelectList构造函数接受用于在元素中呈现valueand的属性名称,但是当使用原始类型的集合(如.textoptionint

问题:

我知道我可以将我的视图模型更改IList<int>IList<SelectListItem>,并创建SelectListItem对象来表示每个int,但这似乎有点荒谬(因为我认为构造函数不应该将值留空,并且应该默认使用文本)。我是否在这里遗漏了一些明显的东西,或者我将不得不在这里放弃使用原始类型?

4

1 回答 1

0

我使用扩展方法解决了这个问题,允许您在视图中编写:

@Html.DropDownListFor(x => x.SelectedSomething, 
                      Model.Somethings.ToSelectList(n => n, v => v), 
                      "Select an Option")

对于 int 集合,您可能需要将其n => n.ToString()用作名称选择器。

这种方法的美妙之处在于您可以将它用于任何类型的可枚举。在您的示例中(带有整数列表),我们只需指定返回元素本身的 lambda,这将导致文本和值在呈现的选项列表中设置为相同的值。

如果您想避免在 Web.config 中导入扩展类的命名空间,请在返回 SelectList 的 ViewModel 上声明一个只读属性,然后从您的视图中访问它。

Web.config 部分看起来像这样(请注意,您需要为程序集和命名空间创建一行)。另请注意,您的 Views 文件夹包含一个单独的 Web.config,它可能会覆盖或扩展您的根 Web.config 中的定义。

<system.web>
    <compilation debug="true" targetFramework="4.0" batch="true">
        <assemblies>
            <add assembly="My.Web.Stuff" />
        </assemblies>
    </compilation>
    <pages>
        <namespaces>
            <add namespace="My.Web.Stuff.Extensions" />
        </namespaces>
    </pages>
</system.web>

这是扩展方法的实现:

/// <summary>
///   Extension methods on IEnumerable.
/// </summary>
public static class SelectListExtensions
{
    /// <summary>
    ///   Converts the source sequence into an IEnumerable of SelectListItem
    /// </summary>
    /// <param name = "items">Source sequence</param>
    /// <param name = "nameSelector">Lambda that specifies the name for the SelectList items</param>
    /// <param name = "valueSelector">Lambda that specifies the value for the SelectList items</param>
    /// <returns>IEnumerable of SelectListItem</returns>
    public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>( this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector )
    {
        return items.ToSelectList( valueSelector, nameSelector, x => false );
    }

    /// <summary>
    ///   Converts the source sequence into an IEnumerable of SelectListItem
    /// </summary>
    /// <param name = "items">Source sequence</param>
    /// <param name = "nameSelector">Lambda that specifies the name for the SelectList items</param>
    /// <param name = "valueSelector">Lambda that specifies the value for the SelectList items</param>
    /// <param name = "selectedItems">Those items that should be selected</param>
    /// <returns>IEnumerable of SelectListItem</returns>
    public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>( this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector, IEnumerable<TValue> selectedItems )
    {
        return items.ToSelectList( valueSelector, nameSelector, x => selectedItems != null && selectedItems.Contains( valueSelector( x ) ) );
    }

    /// <summary>
    ///   Converts the source sequence into an IEnumerable of SelectListItem
    /// </summary>
    /// <param name = "items">Source sequence</param>
    /// <param name = "nameSelector">Lambda that specifies the name for the SelectList items</param>
    /// <param name = "valueSelector">Lambda that specifies the value for the SelectList items</param>
    /// <param name = "selectedValueSelector">Lambda that specifies whether the item should be selected</param>
    /// <returns>IEnumerable of SelectListItem</returns>
    public static IEnumerable<SelectListItem> ToSelectList<TItem, TValue>( this IEnumerable<TItem> items, Func<TItem, TValue> valueSelector, Func<TItem, string> nameSelector, Func<TItem, bool> selectedValueSelector )
    {
        return from item in items
               let value = valueSelector( item )
               select new SelectListItem
                      {
                        Text = nameSelector( item ),
                        Value = value.ToString(),
                        Selected = selectedValueSelector( item )
                      };
    }
}
于 2012-12-19T00:30:56.877 回答