【问题标题】:remove field name in linq select删除 linq select 中的字段名称
【发布时间】:2015-04-25 16:00:26
【问题描述】:

使用 MVC 5 C#。

我有一个列表对象。这是类对象:

public class CameraDevice
{
    public string IPAddress { get; set; }
    public string UDN { get; set; }
    public string DocumentURL { get; set; }
    public string FriendlyName { get; set; }
    public bool IsUSB { get; set; }
    public string Model { get; set; }
    public string Make { get; set; }
    public string DisplayName { get; set; }        
}

使用此对象类型创建一个列表:

var devices = new List<CameraDevice>();

我想用这个列表对象中的一个字段填充一个下拉列表。

所以:

public ActionResult Connection()
{
    var model = new ConnectionData();
    model.Devices = new SelectList(devices.Select(i => new { i.FriendlyName }), "Device");
    return View(model);
}

我的视图模型类是:

public class ConnectionData
{
    [Display(Name = "Device")]
    [Required(ErrorMessage = "Select")]
    public string SelectedDevice { get; set; }
    public IEnumerable<SelectListItem> devices { get; set; }
}

我的 html5 标记是:

@Html.DropDownListFor(m => m.SelectedDevice, Model.Devices, "Select Device", new { @style = "width: 355px;height:21px; border:none;outline:0px;" });

问题是字段名称包含在下拉列表中:

如何删除字段名称?

【问题讨论】:

    标签: c# asp.net-mvc razor asp.net-mvc-5


    【解决方案1】:

    您需要告诉属性名称应该用作 DropDownList 的值和文本。

    以这种方式使用 SelectList 构造函数:

    model.Devices = new SelectList(devices
                                   .Select(i => new { i.FriendlyName }),
                                   "FriendlyName",
                                   "FriendlyName");
    

    第二个参数是 DropDownList 值字段,它将在表单提交时发布到操作,第二个参数是下拉列表的显示文本字段,因为您选择了一个属性,所以我已将 FriendlyName 属性传递给两者。

    或者如果您想使用带有一个参数的 SelectList 构造函数,在这种情况下不要在投影时创建匿名类型,因为您只选择一个属性,所以只需这样做:

    model.Devices = new SelectList(devices
                                   .Select(i => i.FriendlyName));
    

    【讨论】:

    • 嗨,这对我来说是全新的,但现在很有意义。谢谢
    • 这让我发笑,因为我总是忘记 SelectList 是如何工作的,即使我已经做了很多次。所以解决方案是将其粘贴在便笺中。只是一个友好的提醒。
    • @Aizen 说得好……;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多