列表问题中的ASP.NET下拉菜单 [英] ASP.NET Dropdown Menu from List issue

查看:70
本文介绍了列表问题中的ASP.NET下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样填充一个下拉菜单:

I am populating a dropdown menu like so:

@Html.DropDownListFor(model => model.timeSlot, new SelectList(ViewBag.TimeSlots, "id", "timeSlot"), "")

来自这里:

private CPVIPPreviewTimeSlots dbTimeSlots = new CPVIPPreviewTimeSlots();

ViewBag.TimeSlots = dbTimeSlots.Data.ToList();

来自这里:

public class CP_VIP_Preview_TimeSlots
    {
        public int id { get; set; }
        [DisplayName("Time Slots")]
        public string timeSlot { get; set; }
        [DisplayName("Date Slots")]
        public string dateSlot { get; set; }
    }

    public class CPVIPPreviewTimeSlots : DbContext
    {
        public DbSet<CP_VIP_Preview_TimeSlots> Data { get; set; }
    }

现在我要调整此下拉菜单,使其具有timeSlot和dateSlot,如下所示:

Now I am looking to adjust this dropdown menu so it has both timeSlot and dateSlot like so:

@Html.DropDownListFor(model => model.timeSlot, new SelectList(ViewBag.TimeSlots, "id", "dateSlot timeSlot"), "")

但我收到此错误:

does not contain a property with the name 'dateSlot timeSlot'.

我可以同时使用两个下拉菜单吗?我希望这是有道理的.

Can I have both in 1 dropdown? I hope this makes sense.

推荐答案

您需要稍微更改源代码,因为SelectList需要单个字段的名称.但是您可以使用LINQ的Select轻松实现这一点:

You need to change your source a bit, as SelectList expects a name of a single field. But you can easily have this with LINQ's Select:

ViewBag.TimeSlots.Select(ts => new {
    Id = ts.id,
    Text = ts.dateSlot + " " + ts.timeSlot
})

这就是您提供给SelectList的内容.确保您现在提供新属性的名称,并将列表转换为具体类型:

And this is what you give to SelectList. Make sure that you provide names of new properties now, and also cast your list to concrete type:

new SelectList(
    ((IEnumerable<TimeSlot>)ViewBag.TimeSlots).Select(ts => new {
    Id = ts.id,
    Text = ts.dateSlot + " " + ts.timeSlot
}),
"Id", "Text")

这篇关于列表问题中的ASP.NET下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆