c# - 删除 linq select 中的字段名称

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

使用 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>();

我想仅使用此列表对象中的 1 个字段填充下拉列表。

所以:

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

我的 View 模型类是:

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

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

Sample Data

如何删除字段名称?

最佳答案

您需要告诉用作 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));

关于c# - 删除 linq select 中的字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29867485/

相关文章:

javascript - 如何将 Razor boolean 变量传递给 Angular 指令?

c# - 获取被请求/被请求的页面名称

c# - 如何捕获自定义文件夹上的 Outlook 约会删除事件?

c# - 具有 id 的实体已存在且在 CosmosDB 中不同时存在

c# - 将 Interlocked.CompareExchange 与类一起使用

jquery - 使用 jquery post for mvc 3 在部署时不起作用

c# - 覆盖 ASP.NET MVC 事件样式表包

javascript - 将使用 $.get() 呈现的部分 View 中的任何数据传递到 ContentPage

c# - 我无法日期时间验证表单中的字段

asp.net-mvc-3 - 将整个页面从 MVC3 Razor iFrame 页面重定向到不同的 URL