首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将dropdownbox的IEnumerable转换为selectlistItem

将dropdownbox的IEnumerable转换为selectlistItem
EN

Stack Overflow用户
提问于 2016-11-12 06:15:23
回答 3查看 753关注 0票数 0

我有这个方法可以生成3个日期。我希望能够在下拉列表中使用日期。我需要它返回一个selectlistItem。我如何转换它?

代码语言:javascript
复制
        public static IEnumerable<MyDates> GenerateLastThreeDates()
        {
            IEnumerable<MyDates> rangeList = new[] { 1, 2, 3, 4 }.Select(n => DateTime.Now.Subtract(TimeSpan.FromDays(n))) // Transforming the integer (kind of index of days) array into dates.
                .Where(n => n.DayOfWeek != DayOfWeek.Sunday).Take(3) // Removing the Sunday and taking 3 days only.
                .Select(n => new MyDates() { Dateseries = n }); // Converting the date in your MyDates structure.
            return rangeList.ToList();
        }

我试过了,但是没有成功。

代码语言:javascript
复制
        IEnumerable<SelectListItem> myCollection = GenerateLastThreeDates
                                           .Select(i => new SelectListItem()
                                                        {
                                                            Text = i.ToString(), 
                                                            Value = i
                                                        });


        public class MyDates
        {
            public DateTime Dateseries { get; set; }
        }
EN

回答 3

Stack Overflow用户

发布于 2016-11-12 06:25:05

将controller

  • Convert instances

  • Store data中的日期生成到SelectListItem ViewData中的列表中-这就是如何使用ViewData:

将非模型(即单向数据,而不是双向数据)传递到列表中的视图

例如:

控制器

代码语言:javascript
复制
public class FooController : Controller
{
    private static IEnumerable<SelectListItem> GenerateLastThreeDates()
    {
        // note that your code should be timezone-aware, so consider using DateTimeOffset instead of DateTime
        // also, never reference DateTime.Today (or Now, or UtcNow) in a loop - because the value can change in successive calls, instead you should store the value and re-use the cached copy
        DateTime now = DateTime.Today; 
        return Enumerable.Range( 1, 4 )
            .Select( n => now.AddDays( -n ) )
            .Where( d => d.DayOfWeek != DayOfWeek.Sunday )
            .Take( 3 )
            .Select( d => new SelectListItem()
            {
                Value = d.ToString("o"), // "o" for the RoundTrip format
                Text = d.ToString("d")
            } );
    }

    [HttpGet]
    public ActionResult Index()
    {
        this.ViewData["dates"] = GenerateLastThreeDates();
        return this.View( new IndexViewModel() );
    }

    [HttpPost]
    public ActionResult Index(IndexViewModel viewModel)
    {
        if( this.ModelState.IsValid )
        {
            DoSomething( viewModel.SelectedDate );

            return this.RedirectToAction( nameof(this.Index) );
        }
        else
        {
            this.ViewData["dates"] = GenerateLastThreeDates();
            return this.View( viewModel );
        }
    }

}

ViewModel.cs

代码语言:javascript
复制
public class IndexViewModel {

    [Required]
    public DateTime SelectedDate { get; set; }
}

View.cshtml

代码语言:javascript
复制
@{ IEnumerable<SelectListItem> dates = (IEnumerable<SelectListItem>)this.ViewData["dates"]; }

<p>Select a date: @Html.DropDownListFor( m = m.SelectedDate, dates )</p>
票数 0
EN

Stack Overflow用户

发布于 2016-11-12 07:07:56

您的GenerateLastThreeDates方法返回一个MyDates集合,该集合中的每个项都有一个Dateseries属性,您将为该属性设置日期和时间。因此,在执行select方法调用时,基本上需要选择该属性。

代码语言:javascript
复制
var myCollection = GenerateLastThreeDates()
                     .Select(i => new SelectListItem
                                      {
                                        Text = i.Dateseries.ToString(), 
                                        Value = i.Dateseries.ToString()
                                      });

myCollection是SelectListItem的集合,其中的Text和value属性保存日期值的测试版本。您可以使用此类通过Html.DropDownListForHtml.DropDownList辅助方法来构建select元素。

票数 0
EN

Stack Overflow用户

发布于 2016-11-12 08:11:19

我通常只像这样定义扩展方法:

代码语言:javascript
复制
    public static List<SelectListItem> ToSelectListItems<T>(this IEnumerable<T> collection, Func<T, object> textSelector, Func<T, object> valueSelector, string emptyText = "- Choose-",
        string emptyValue = null)
    {
        var result = new List<SelectListItem>();

        if (collection != null)
        {
            var items = collection
                .Select(x => new SelectListItem
                {
                    Text = textSelector(x)?.ToString(),
                    Value = valueSelector(x)?.ToString()
                })
                .ToList();
            result.AddRange(items);
        }

        if (emptyText != null)
        {
            result.Insert(0, new SelectListItem { Text = emptyText, Value = emptyValue ?? string.Empty });
        }
        return result;
    }

然后:

1)将可能的值作为任意IEnumerable<T>添加到模型中

代码语言:javascript
复制
public class MyModel
{
    public int CountryId { get; set; }
    public List<Country> AllCountries { get; set; } = new List<Country>();
}

2)在控制器操作中填充可能的值:

代码语言:javascript
复制
public ActionResult Index()
{
    var model = new MyModel
    {
        AllCountries = _repository.GetCountries();
    };

    return View(model);
}

3)直接在视图中使用该扩展方法:

代码语言:javascript
复制
@Html.DropDownListFor(x => x.CountryId, Model.AllCountries.ToSelectListItems(x => x.CountryName, x => x.CountryId))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40557066

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档