加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用DropDownListFor和原始类型列表的正确方法?

发布时间:2020-12-15 06:24:14 所属栏目:百科 来源:网络整理
导读:以下是相关代码.记住你,我在记事本中做了这个,而不是在我的代码中复制我的项目在工作.如果我拼错了一个类名,假设我的代码中没有拼写错误.没有编译错误. 模型: public class MyViewModel{ public int SelectedSomething { get; set; } public IListint Somet
以下是相关代码.记住你,我在记事本中做了这个,而不是在我的代码中复制我的项目在工作.如果我拼错了一个类名,假设我的代码中没有拼写错误.没有编译错误.

模型:

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

视图(Razor):

@Html.DropDownListFor(x => x.SelectedSomething,new SelectList(Model.Somethings,Model.SelectedSomething),"Select an 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,但是当使用像int这样的原始类型的集合时,它是没有用的(我可以看到).

题:

我知道我可以改变我的视图模型的IList< int>到IList< SelectListItem>,并创建SelectListItem对象来表示每个int,但这似乎有点可笑(因为我认为构造函数不应该将值留空,并且应该默认使用文本).我在这里缺少一些明显的东西,还是我不得不在这里离开使用原始类型?

解决方法

我使用扩展方法解决了这个问题,允许你在你的视图中写:
@Html.DropDownListFor(x => x.SelectedSomething,Model.Somethings.ToSelectList(n => n,v => v),"Select an Option")

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

这种方法的优点是可以将其用于任何类型的枚举.在你的例子中(使用整数列表),我们只需指定返回元素本身的lambdas,这将导致在渲染的选项列表中将文本和值设置为相同的值.

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

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,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,string> nameSelector,IEnumerable<TValue> selectedItems )
    {
        return items.ToSelectList( valueSelector,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,bool> selectedValueSelector )
    {
        return from item in items
               let value = valueSelector( item )
               select new SelectListItem
                      {
                        Text = nameSelector( item ),Value = value.ToString(),Selected = selectedValueSelector( item )
                      };
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读