![](/img/trans.png)
[英]Linq select a single field using a string containing the name of the field
[英]remove field name in linq select
使用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);
}
我的viewmodel類是:
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;" });
問題在於字段名稱包含在下拉列表中:
如何刪除字段名稱?
您需要告訴屬性名稱,該屬性名稱應用作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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.