将IEnumerable转换为下拉框的selectlistItem

时间:2016-11-11 22:15:23

标签: linq c#-4.0

我有这个方法可以生成3个日期。我希望能够使用日期 下拉菜单。我需要它来返回一个selectlistItem。我该怎么转换呢?

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

我尝试了这个,但没有运气。

        IEnumerable<SelectListItem> myCollection = GenerateLastThreeDates
                                           .Select(i => new SelectListItem()
                                                        {
                                                            Text = i.ToString(), 
                                                            Value = i
                                                        });


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

3 个答案:

答案 0 :(得分:0)

  1. 在控制器中生成日期
  2. 将日期转换为ViewData个实例
  3. 将列表存储在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 ); } } 中 - 这是将非模型(即单向数据,而非双向数据)传递给控制器​​视图的方式
  4. 使用ViewData:
  5. 渲染列表

    例如:

    控制器

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

    }

    ViewModel.cs

    @{ IEnumerable<SelectListItem> dates = (IEnumerable<SelectListItem>)this.ViewData["dates"]; }
    
    <p>Select a date: @Html.DropDownListFor( m = m.SelectedDate, dates )</p>
    

    View.cshtml

    $('.btn-group.bootstrap-select.open input').val('');
    $('.selectpicker').selectpicker('refresh');
    

答案 1 :(得分:0)

您的GenerateLastThreeDates方法返回MyDates的集合,该集合中的每个项目都有一个Dateseries属性,您要为其设置日期时间。所以基本上你需要在进行Select方法调用时选择该属性。

var myCollection = GenerateLastThreeDates()
                     .Select(i => new SelectListItem
                                      {
                                        Text = i.Dateseries.ToString(), 
                                        Value = i.Dateseries.ToString()
                                      });

myCollection是SelectListItem的集合,其中Text和Value属性包含日期值的测试版本。您可以使用此碰撞使用Html.DropDownListForHtml.DropDownList辅助方法构建select元素。

答案 2 :(得分:0)

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

    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>

public class MyModel
{
    public int CountryId { get; set; }
    public List<Country> AllCountries { get; set; } = new List<Country>();
}

2)在控制器动作中填写可能的值:

public ActionResult Index()
{
    var model = new MyModel
    {
        AllCountries = _repository.GetCountries();
    };

    return View(model);
}

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

@Html.DropDownListFor(x => x.CountryId, Model.AllCountries.ToSelectListItems(x => x.CountryName, x => x.CountryId))