c# - 将 DropDownListFor 与原始类型列表一起使用的正确方法?

标签 c# asp.net-mvc-3 razor

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

型号:

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

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

Controller :

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

View ( Razor ):

@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 constructor接收用于呈现 value 的属性名称和 textoption元素,但在使用像 int 这样的原始类型的集合时,它没有用(我可以看到) .

问题:

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

最佳答案

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

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

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

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

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

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 )
                      };
    }
}

关于c# - 将 DropDownListFor 与原始类型列表一起使用的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13943649/

相关文章:

c# - 使用 LINQ 进行标记枚举合并(组合的逆)

c# - 获取和处理 MVC 中输入的数据 - 简单

asp.net-mvc - ASP.Net MVC 3 网格

javascript - 像 '&' 和 '£' 这样的特殊字符会剪切我传递的 Twitter 文本

html - 以下 CSS 和 HTML 有什么问题?

twitter-bootstrap - 无法将 Bootstrap 类应用于我的 EditorFor

c# - XML 文档注释中的 XML (C#)

c# - 你如何在 C# 中获取用户的国家/地区名称?

c# - 如何快速操作 byte[] 中的数据?

c# - 在 View 中禁用复选框